PHP Forms Handling
Forms are the main way to get data from the visitors of your website: a login, a contact form, a registration, a search box. PHP reads the data of a form using special variables called superglobals, like $_GET and $_POST.
A simple form
The method attribute tells how the data is sent, and the action attribute tells which file receives it.
<form method="post" action="process.php">
<label>Name:</label>
<input type="text" name="name">
<label>Email:</label>
<input type="email" name="email">
<button type="submit">Send</button>
</form>
Every input needs a name. That name becomes the key in $_POST["name"].
GET and POST
| GET | POST | |
|---|---|---|
| Data is sent | In the URL (visible) | In the request body (not visible in the URL) |
| Use for | Search, filters, page numbers | Login, registration, sending data that changes something |
| Bookmark | Possible | Not possible |
| Limit | About 2000 characters | Much bigger |
| PHP variable | $_GET | $_POST |
A detailed comparison is in the interview question difference between GET and POST. Never send a password with GET.
Process the form data
This is process.php. It checks that the form was sent with POST, validates the data, and escapes the text before showing it.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = filter_var($_POST["email"] ?? "", FILTER_VALIDATE_EMAIL);
if ($name === "") {
echo "Name is required.";
} elseif (!$email) {
echo "Please enter a valid email address.";
} else {
echo "Thank you, " . htmlspecialchars($name) . "! We will write to " . htmlspecialchars($email);
}
}
?>
Output:
Thank you, Robin! We will write to robin@example.com
$_SERVER["REQUEST_METHOD"]tells if the page was opened normally (GET) or by a form (POST).??avoids a warning if the field is missing.trim()removes extra spaces, andfilter_var()validates the email.htmlspecialchars()keeps the page safe from XSS when you print the data.
Validation checklist
- Check that required fields are not empty.
- Check the format: email, number, date.
- Check the length and the allowed values.
- Always validate on the server. Browser checks (like
required) can be skipped by a user. - Show a clear error next to the field, and keep the typed values in the form.
Protect your forms with a CSRF token, see What is CSRF?. If the form saves data in a database, use prepared statements, and for file fields read PHP File Upload.
| Exercises & Assignments |
|---|
| Create a PHP Form with 2 fields Name and Hobbies |