The Bridge Between User and Server
Nearly every website you use needs to collect information from you. Whether you're using a search engine, logging into an account, or leaving a comment, you are interacting with an HTML Form. Forms are the primary way to send data from the user's browser (client-side) to the server (server-side), and PHP is excellent at processing this data.
The HTML Form Element
An HTML form is defined with the <form>
tag. The two most important attributes of this tag are:
action
: This specifies the path to the PHP file that will process the form data.method
: This specifies the HTTP method to be used. The two most common methods areGET
andPOST
.
<form action="welcome.php" method="post">
Name: <input type="text" name="username">
<button type="submit">Submit</button>
</form>
GET vs. POST
Choosing the right method is important for functionality and security.
GET Method
When you submit a form with the GET
method, the data is sent as URL parameters. You will see it in the browser's address bar.
http://example.com/search.php?query=php+tutorials
- Visibility: All data is visible in the URL.
- Limitations: There is a limit to the amount of data you can send (about 2000 characters).
- Best for: Non-sensitive data, like search queries or page numbers. Should never be used for passwords or personal information.
POST Method
When you submit a form with the POST
method, the data is sent in the body of the HTTP request. It is not visible in the URL.
- Visibility: Data is hidden from the address bar.
- Limitations: No limit on the amount of data you can send.
- Best for: Sensitive information like logins, contact forms, and any data that modifies the database.
Processing Form Data in PHP
PHP makes it easy to access the data sent from a form using special built-in arrays called superglobals:
$_GET
: An associative array containing data sent via the GET method.$_POST
: An associative array containing data sent via the POST method.
Example: A Simple Welcome Form
Let's create two files. Save the first as form.html
and the second as welcome.php
in your htdocs/php-course
folder.
form.html:
<!DOCTYPE html>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
welcome.php:
<?php
// Use htmlspecialchars() to prevent security issues like XSS
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
echo "Welcome, " . $name . "!<br>";
echo "Your email address is: " . $email;
?>
Now, open http://localhost/php-course/form.html
in your browser, fill out the form, and click submit. The welcome.php
script will process your input and display a personalized greeting. You've just built your first interactive web feature!