Session 3.6 – PHP Forms: GET and POST Methods

Module 3: PHP Basics | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Understand HTTP request methods GET and POST
  • Create HTML forms and process form data in PHP
  • Differentiate between GET and POST usage scenarios
  • Handle form submissions securely
  • Validate and sanitize user input
  • Build interactive web forms with PHP

Introduction

HTML forms allow users to interact with web applications by submitting data. PHP provides powerful capabilities to process form data using GET and POST methods.

Key Insight

GET and POST are HTTP request methods that determine how form data is sent to the server. Choosing the right method is crucial for security and functionality.

GET Method

GET appends form data to the URL as query parameters. Data is visible in the URL.

Basic GET Form
<!-- HTML Form -->
<form action="process.php" method="GET">
    <label>Name:</label>
    <input type="text" name="username">

    <label>Age:</label>
    <input type="number" name="age">

    <button type="submit">Submit</button>
</form>
Processing GET Data
<?php
// process.php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    // Check if data exists
    if (isset($_GET['username']) && isset($_GET['age'])) {
        $username = $_GET['username'];
        $age = $_GET['age'];

        echo "Name: " . htmlspecialchars($username) . "<br>";
        echo "Age: " . htmlspecialchars($age);
    }
}
?>
GET Characteristics
  • Visible: Data appears in URL (e.g., ?name=John&age=30)
  • Bookmarkable: URLs with parameters can be saved
  • Limited size: Maximum ~2048 characters
  • Not secure: Sensitive data exposed in URL
  • Cacheable: Browsers can cache GET requests
  • Idempotent: Multiple identical requests have same effect
When to Use GET
  • Search forms
  • Filtering and sorting
  • Pagination links
  • Shareable URLs
  • Non-sensitive data retrieval

POST Method

POST sends data in the HTTP request body, hidden from the URL. More secure for sensitive information.

Basic POST Form
<form action="register.php" method="POST">
    <label>Username:</label>
    <input type="text" name="username" required>

    <label>Email:</label>
    <input type="email" name="email" required>

    <label>Password:</label>
    <input type="password" name="password" required>

    <button type="submit">Register</button>
</form>
Processing POST Data
<?php
// register.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Use null coalescing operator for safety
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';

    // Validate input
    if (empty($username) || empty($email) || empty($password)) {
        die("All fields are required");
    }

    // Sanitize input
    $username = htmlspecialchars(trim($username));
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die("Invalid email format");
    }

    // Hash password (NEVER store plain text passwords!)
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Process registration (save to database, etc.)
    echo "Registration successful for: " . $username;
}
?>
POST Characteristics
  • Hidden: Data not visible in URL
  • Secure: Better for sensitive information
  • Larger size: Can handle large amounts of data
  • Not bookmarkable: Cannot save form state in URL
  • Not cached: Fresh request each time
  • Can modify: Intended for operations that change server state
When to Use POST
  • Login forms
  • Registration forms
  • File uploads
  • Creating/updating/deleting data
  • Sensitive information
  • Large data submissions

Security Considerations

Input Validation and Sanitization
<?php
// Always validate and sanitize user input

// 1. Sanitize HTML special characters (prevent XSS)
$safe_input = htmlspecialchars($_POST['user_input'], ENT_QUOTES, 'UTF-8');

// 2. Remove whitespace
$trimmed = trim($_POST['name']);

// 3. Validate and sanitize email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email format");
}

// 4. Sanitize URL
$url = filter_var($_POST['website'], FILTER_SANITIZE_URL);
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    die("Invalid URL");
}

// 5. Strip HTML tags
$clean_text = strip_tags($_POST['message']);

// 6. Validate integer
$age = filter_var($_POST['age'], FILTER_VALIDATE_INT);
if ($age === false || $age < 0 || $age > 150) {
    die("Invalid age");
}

// 7. Validate float
$price = filter_var($_POST['price'], FILTER_VALIDATE_FLOAT);

// 8. Custom validation with regex
$phone = $_POST['phone'];
if (!preg_match('/^[0-9]{10}$/', $phone)) {
    die("Invalid phone number format");
}
?>
CSRF Protection
<?php
// Protect against Cross-Site Request Forgery
session_start();

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<!-- Include token in form -->
<form method="POST">
    <input type="hidden" name="csrf_token"
           value="<?php echo $_SESSION['csrf_token']; ?>">

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

<?php
// Verify CSRF token on form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_POST['csrf_token']) ||
        $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF token validation failed");
    }

    // Process form securely
    // ...
}
?>
SQL Injection Prevention
<?php
// NEVER concatenate user input directly into SQL queries!

// ❌ BAD - Vulnerable to SQL injection
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$username'";

// ✅ GOOD - Use prepared statements
$username = $_POST['username'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

// Or with named parameters
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
?>

Practical Examples

Complete Login System
<!-- login.php -->
<?php
session_start();

$error = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    // In real application, check against database
    // This is just for demonstration
    $stored_hash = '$2y$10$example_hash_from_database';

    if (password_verify($password, $stored_hash)) {
        $_SESSION['logged_in'] = true;
        $_SESSION['username'] = $username;
        header("Location: dashboard.php");
        exit;
    } else {
        $error = "Invalid username or password";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 400px; margin: 50px auto; }
        .form-group { margin-bottom: 15px; }
        input { width: 100%; padding: 8px; }
        button { width: 100%; padding: 10px; background: #007bff; color: white; border: none; }
        .error { color: red; padding: 10px; background: #ffe6e6; }
    </style>
</head>
<body>
    <h2>Login</h2>

    <?php if ($error): ?>
        <div class="error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="form-group">
            <label>Username:</label>
            <input type="text" name="username" required>
        </div>

        <div class="form-group">
            <label>Password:</label>
            <input type="password" name="password" required>
        </div>

        <button type="submit">Login</button>
    </form>
</body>
</html>
File Upload Form
<!-- upload.php -->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Check for upload errors
    if ($file['error'] === UPLOAD_ERR_OK) {
        $upload_dir = 'uploads/';

        // Create upload directory if it doesn't exist
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        // Get file extension
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        // Validate file type
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
        if (!in_array($file_extension, $allowed_types)) {
            die("Invalid file type. Allowed: " . implode(', ', $allowed_types));
        }

        // Validate file size (5MB max)
        $max_size = 5 * 1024 * 1024;
        if ($file['size'] > $max_size) {
            die("File too large. Maximum size: 5MB");
        }

        // Generate unique filename
        $new_filename = uniqid() . '.' . $file_extension;
        $destination = $upload_dir . $new_filename;

        // Move uploaded file
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            echo "File uploaded successfully: " . htmlspecialchars($new_filename);
        } else {
            echo "Error uploading file";
        }
    } else {
        echo "Upload error code: " . $file['error'];
    }
}
?>

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="file" required>
    <button type="submit">Upload</button>
</form>
Multi-Step Form
<?php
session_start();

// Step 1: Personal Information
if (!isset($_SESSION['step'])) {
    $_SESSION['step'] = 1;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($_SESSION['step'] == 1) {
        $_SESSION['name'] = $_POST['name'];
        $_SESSION['email'] = $_POST['email'];
        $_SESSION['step'] = 2;
    } elseif ($_SESSION['step'] == 2) {
        $_SESSION['address'] = $_POST['address'];
        $_SESSION['phone'] = $_POST['phone'];
        $_SESSION['step'] = 3;

        // Process complete form
        echo "<h2>Registration Complete!</h2>";
        echo "Name: " . htmlspecialchars($_SESSION['name']) . "<br>";
        echo "Email: " . htmlspecialchars($_SESSION['email']) . "<br>";
        echo "Address: " . htmlspecialchars($_SESSION['address']) . "<br>";
        echo "Phone: " . htmlspecialchars($_SESSION['phone']);

        // Clear session
        session_destroy();
        exit;
    }
}

// Display current step
if ($_SESSION['step'] == 1) {
    echo '<form method="POST">
            <h2>Step 1: Personal Information</h2>
            <input type="text" name="name" placeholder="Name" required><br>
            <input type="email" name="email" placeholder="Email" required><br>
            <button type="submit">Next</button>
          </form>';
} elseif ($_SESSION['step'] == 2) {
    echo '<form method="POST">
            <h2>Step 2: Contact Information</h2>
            <input type="text" name="address" placeholder="Address" required><br>
            <input type="tel" name="phone" placeholder="Phone" required><br>
            <button type="submit">Complete</button>
          </form>';
}
?>

Session Summary

Key Points
  • GET Method: Data in URL, visible, limited size, for retrieval
  • POST Method: Data in body, hidden, larger size, for sensitive data
  • $_GET: Superglobal array for accessing GET parameters
  • $_POST: Superglobal array for accessing POST data
  • $_FILES: Superglobal for file uploads (requires enctype)
  • Security: Always validate, sanitize, and use prepared statements
  • CSRF: Protect forms with CSRF tokens
Best Practices
  • Use POST for forms that modify data or contain sensitive information
  • Use GET for search forms, filters, and shareable URLs
  • Always validate and sanitize user input
  • Implement CSRF protection for all POST forms
  • Use htmlspecialchars() to prevent XSS attacks
  • Use prepared statements to prevent SQL injection
  • Never trust user input - validate everything
  • Hash passwords with password_hash(), never store plain text
Next Session Preview

In the next session, we'll explore Regular Expressions and Server-Side Validation, learning powerful pattern matching techniques for validating complex user input like emails, phone numbers, and custom formats.