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:
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.
- Check if required fields exist:
isset($_POST['field']) - Check if fields are not empty:
!empty($_POST['field']) - Validate format: email, phone, etc.
- Sanitize for output:
htmlspecialchars() - 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
$_GETand$_POSTsuperglobals 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