Form Handling

Processing HTML form submissions with PHP superglobals

GET vs POST

HTML forms can submit data using two HTTP methods. The choice affects where the data travels and how it behaves:

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 provides superglobal arrays for form data. These are automatically populated from the HTTP request:

Checking Request Method

A common PHP pattern is the self-submitting form: one file that shows the form on GET and processes data on POST.

...'; } ?>

Security: Always Sanitize Output

User input is untrusted. If you echo it directly into HTML, an attacker can inject JavaScript:

// 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 in other users' browsers. The right version displays it as harmless text.

HTML Form Basics

The HTML form provides the user interface. Each input's name attribute becomes the key in PHP's superglobal arrays:

Form Validation Checklist

Server-side validation is mandatory. Client-side validation (HTML5 attributes, JavaScript) improves the user experience but can always be bypassed.

  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 (covered in the database tutorial)

Summary

  • HTML forms send data via GET (URL query string) or POST (request body)
  • PHP provides $_GET and $_POST superglobals to access form data
  • Use $_SERVER['REQUEST_METHOD'] to distinguish form display from form processing
  • Always sanitize output with htmlspecialchars() to prevent XSS attacks
  • Server-side validation is mandatory — client-side validation can be bypassed