PHP Form Handling and Validation

PHP Form Handling and Validation

Handling HTML forms securely is one of the most important PHP skills. Always sanitize and validate every piece of user input.

1 - HTML Form

<form method="POST" action="">
    <input type="text"  name="name">
    <input type="email" name="email">
    <button type="submit">Submit</button>
</form>

2 - Receiving Data

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name  = $_POST["name"]  ?? "";
    $email = $_POST["email"] ?? "";
}

3 - Sanitize

$name  = htmlspecialchars(trim($name));
$email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);

4 - Validate

$errors = [];

if (strlen($name) < 2) {
    $errors[] = "Name must be at least 2 characters.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Enter a valid email address.";
}

if (empty($errors)) {
    // safe to process
} else {
    foreach ($errors as $e) {
        echo "<p style='color:red'>$e</p>";
    }
}

5 - CSRF Protection

// Generate token on form load
session_start();
$_SESSION["csrf"] = bin2hex(random_bytes(32));

// In HTML form
echo "<input type='hidden' name='csrf' value='" . $_SESSION["csrf"] . "'>";

// Validate on submit
if (!hash_equals($_SESSION["csrf"], $_POST["csrf"] ?? "")) {
    die("CSRF check failed.");
}

Note: Always run htmlspecialchars() when outputting user-supplied data in HTML. This prevents XSS (Cross-Site Scripting) attacks where malicious JavaScript is injected into your pages.

-Tip-