Module 02: Form Handling

Learning Objectives

Demo Files

get-example.php Search form using GET - see data in URL

post-example.php Contact form using POST - data hidden in request body

combined.php Self-submitting form with validation

GET vs POST

Feature GET POST
Data location URL query string Request body
Visibility Visible in URL, logs, history Hidden (but not encrypted!)
Size limit ~2KB (URL length limit) Server-configurable (usually MB)
Bookmarkable Yes No
Cached Yes No
Use for Search, filters, navigation Login, signup, data changes

Accessing Form Data

<?php
// GET data (from URL: ?name=Alice&age=25)
$name = $_GET['name'] ?? '';   // 'Alice'
$age = $_GET['age'] ?? '';     // '25'

// POST data (from form submission)
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

// The ?? operator provides a default if key doesn't exist
// This prevents "undefined index" warnings
?>

Checking Request Method

<?php
// Common pattern: show form on GET, process on POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Form was submitted - process the data
    $name = $_POST['name'] ?? '';
    echo "Processing form for: " . htmlspecialchars($name);
} else {
    // Show the form
    echo '<form method="POST">...</form>';
}
?>

Security: Always Sanitize Output!

// WRONG - XSS vulnerability!
echo "Hello, " . $_POST['name'];

// RIGHT - escape HTML entities
echo "Hello, " . htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');

If a user enters <script>alert('hacked')</script> as their name, the wrong version executes that JavaScript. The right version displays it as harmless text.

HTML Form Basics

<form method="POST" action="process.php">
    <!-- Text input -->
    <input type="text" name="username">

    <!-- Email (browser validates format) -->
    <input type="email" name="email">

    <!-- Password (hidden characters) -->
    <input type="password" name="password">

    <!-- Dropdown -->
    <select name="country">
        <option value="us">United States</option>
        <option value="uk">United Kingdom</option>
    </select>

    <!-- Submit button -->
    <button type="submit">Submit</button>
</form>

The name attribute is crucial! It becomes the key in $_GET or $_POST.

If you forget the name attribute, PHP won't receive that field's data.

Form Validation Checklist

  1. Check if required fields exist: isset($_POST['field'])
  2. Check if fields are not empty: !empty($_POST['field'])
  3. Validate format: email, phone, etc.
  4. Sanitize for output: htmlspecialchars()
  5. Sanitize for database: prepared statements (not covered here)

← Previous: Hello World | Tutorial Home | Next: Headers & Metadata →