Form Handling

Learn to process user input with GET and POST methods, and validate form data.

Form Data Processing

Forms are the primary way to collect user input. Learn how to handle form data securely in PHP.

GET vs POST

  • GET: Data visible in URL, limited size (~2KB), good for searches
  • POST: Data hidden in request body, larger data limit, good for forms
  • Access with $_GET['name'] and $_POST['name']
HTML Form
<!-- GET Form (data visible in URL) -->
<form action="search.php" method="GET">
    <input type="text" name="query" placeholder="Search...">
    <button type="submit">Search</button>
</form>
<!-- URL becomes: search.php?query=value -->

<!-- POST Form (data hidden) -->
<form action="process.php" method="POST">
    <input type="text" name="name">
    <input type="email" name="email">
    <input type="password" name="password">
    <button type="submit">Register</button>
</form>

Processing Form Data

PHP Form Handling
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Get form data safely
    $name = $_POST["name"] ?? "";
    $email = $_POST["email"] ?? "";
    
    // Sanitize input
    $name = htmlspecialchars(trim($name));
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    
    // Validate
    if (empty($name)) {
        echo "Name is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format";
    } else {
        echo "Welcome, $name!";
    }
}

// Display submitted values
$name_value = $_POST["name"] ?? "";
?>

<form method="POST">
    <input type="text" name="name" value="<?= htmlspecialchars($name_value) ?>">
    <input type="email" name="email">
    <button type="submit">Submit</button>
</form>

Security Warning: Always validate and sanitize user input. Never trust form data blindly. Use prepared statements for database queries.

Form Validation

PHP Validation
<?php
$errors = [];

// Required field
if (empty($_POST["name"])) {
    $errors[] = "Name is required";
}

// Email validation
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Please enter a valid email";
}

// Number validation
if (!filter_var($_POST["age"], FILTER_VALIDATE_INT)) {
    $errors[] = "Age must be a number";
}

// Length validation
if (strlen($_POST["password"]) < 8) {
    $errors[] = "Password must be at least 8 characters";
}

// Pattern matching
if (!preg_match("/^[a-zA-Z ]*$/", $_POST["name"])) {
    $errors[] = "Only letters and spaces allowed";
}

// Display errors
if (!empty($errors)) {
    foreach ($errors as $error) {
        echo "<div class='error'>$error</div>";
    }
}
?>

Hands-on Exercises

Exercise 1: Create a login form with username and password fields
Exercise 2: Add validation for email format and password length
Exercise 3: Sanitize all form inputs before displaying them
Exercise 4: Create a registration form with password confirmation
Exercise 5: Add error messages that appear above the form