PHP Tutorial · PHP for the Web · Lesson 21 of 38

PHP Form Handling

Handle POST forms, validate fields and show errors.

A complete form

The same script shows the form and handles the submission. It checks $_SERVER["REQUEST_METHOD"], validates each field, and re-displays values safely:

<?php
$errors = [];
$email = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = trim($_POST["email"] ?? "");
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors["email"] = "Enter a valid email address.";
    }
    if (strlen($_POST["password"] ?? "") < 8) {
        $errors["password"] = "Password must be at least 8 characters.";
    }
    if (!$errors) {
        // save the user, then redirect (Post/Redirect/Get)
        header("Location: /welcome.php");
        exit;
    }
}
?>
<form method="post">
  <input name="email" value="<?= htmlspecialchars($email) ?>">
  <?= $errors["email"] ?? "" ?>
  <input name="password" type="password">
  <?= $errors["password"] ?? "" ?>
  <button>Sign up</button>
</form>

The validation logic

Here's the validation part on its own so you can run and change it:

Example 1Try it yourself
<?php
function validateSignup(array $input): array
{
    $errors = [];
    if (!filter_var(trim($input["email"] ?? ""), FILTER_VALIDATE_EMAIL)) {
        $errors["email"] = "Enter a valid email address.";
    }
    if (strlen($input["password"] ?? "") < 8) {
        $errors["password"] = "Password must be at least 8 characters.";
    }
    return $errors;
}

print_r(validateSignup(["email" => "ada@", "password" => "123"]));
print_r(validateSignup(["email" => "[email protected]", "password" => "correct horse"]));
$hash = password_hash("correct horse", PASSWORD_DEFAULT);
var_dump(password_verify("correct horse", $hash), password_verify("wrong", $hash));

Output

Array
(
    [email] => Enter a valid email address.
    [password] => Password must be at least 8 characters.
)
Array
(
)
bool(true)
bool(false)

Security checklist

  • Validate on the server — browser checks can be bypassed.
  • Escape output with htmlspecialchars().
  • Hash passwords with password_hash(); check them with password_verify().
  • Protect forms against CSRF with a random token stored in the session.

Test yourself

Which function should you use to store a user's password?

  1. md5()
  2. sha1()
  3. password_hash()
  4. base64_encode()
Show answer

Answer: password_hash()