How forms reach PHP
When a form is submitted, PHP receives the values in superglobal arrays: $_GET (values in the URL) and $_POST (values in the request body). Use POST for anything private or that changes data.
A contact form
<?php
$errors = [];
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "") {
$errors[] = "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Enter a valid email.";
}
if (!$errors) {
echo "Thank you, " . htmlspecialchars($name) . "!";
}
}
?>
<form method="post">
<input name="name" value="<?= htmlspecialchars($name) ?>" placeholder="Name">
<input name="email" value="<?= htmlspecialchars($email) ?>" placeholder="Email">
<button>Send</button>
</form>
<?php foreach ($errors as $e): ?>
<p style="color:red"><?= htmlspecialchars($e) ?></p>
<?php endforeach; ?>Security rules you must follow
- Never trust input. Validate on the server even if the browser also checks.
- Escape output. Use
htmlspecialchars()whenever you print user data, to prevent cross-site scripting (XSS). - Use prepared statements for database queries (next lessons).
- Protect forms with a CSRF token in real applications.
File uploads
Check the file size and type on the server, generate your own file name and store uploads outside directories where scripts can run.
Practice
Build a registration form that validates name, email and password length, remembers the values after an error and shows friendly error messages.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Make a contact form that posts to a PHP script.
- Validate that name and email are not empty and that the email is valid.
- Escape output with htmlspecialchars.
Common mistakes
- Printing user input without escaping.
- Trusting client-side validation only.
Quick check
What is the difference between GET and POST?
GET puts data in the URL; POST sends it in the request body.
Why use htmlspecialchars?
To stop user input being interpreted as HTML.