📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Form Processing

Form Processing

6 min read Quiz at the end
HTML forms send data to PHP through $_GET or $_POST. Always validate that data meets requirements and sanitize it before use. Use htmlspecialchars() when displaying user input and PDO prepared statements for database queries.

Processing HTML Forms

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Sanitize inputs
    $name  = htmlspecialchars(trim($_POST["name"]  ?? ""));
    $email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
    $age   = filter_input(INPUT_POST, "age",   FILTER_VALIDATE_INT);

    // Validate
    $errors = [];
    if (empty($name))  $errors[] = "Name is required";
    if (!$email)       $errors[] = "Valid email required";
    if (!$age || $age < 18) $errors[] = "Must be 18+";

    if (empty($errors)) {
        // Save to database
        echo "Success!";
    }
}
?>
<form method="POST">
  <input name="name" value="<?= htmlspecialchars($name ?? '') ?>">
  <input name="email" type="email">
  <input name="age" type="number">
  <button type="submit">Submit</button>
</form>
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which filter validates an email address?
💡 filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL) returns the email or false.
2. What does htmlspecialchars() protect against?
💡 htmlspecialchars() escapes HTML entities, preventing XSS when outputting user input.
3. How should you check the request method?
💡 $_SERVER["REQUEST_METHOD"] contains the HTTP method (GET, POST, etc.).
4. Which function sanitizes and validates inputs?
💡 filter_input() and filter_var() provide built-in sanitization and validation filters.
5. What does the null coalescing operator ?? do?
💡 $val = $_POST["name"] ?? "default" returns "default" if "name" is not set or null.