Lesson 9 โข Intermediate
Forms & User Input ๐
Handle HTML form submissions securely โ sanitize, validate, and process user data with PHP's built-in filter functions.
What You'll Learn in This Lesson
- โข GET vs POST: when to use each method
- โข Sanitizing input: htmlspecialchars, trim, strip_tags
- โข Validating with filter_var and custom rules
- โข Sticky forms that preserve user input on errors
- โข CSRF protection with tokens
Try It: Form Processing
Sanitize and validate a contact form submission step by step
// PHP Forms & User Input (simulated in JavaScript)
console.log("=== GET vs POST Methods ===");
console.log();
console.log("GET โ data in URL: example.com/search?q=php&page=2");
console.log("POST โ data in request body (hidden from URL)");
console.log();
console.log("Feature | GET | POST");
console.log("โโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโ");
console.log("Visibility | In URL | Hidden");
console.log("Size limit | ~2048 chars
...Try It: Validation & Security
Use PHP filter functions, sticky forms, and CSRF protection
// Advanced Form Validation Patterns
console.log("=== PHP Filter Functions ===");
console.log();
console.log("PHP has built-in filter functions for validation:");
console.log();
// Simulate filter_var validations
let testCases = [
{ input: "alice@example.com", filter: "FILTER_VALIDATE_EMAIL", valid: true },
{ input: "not-an-email", filter: "FILTER_VALIDATE_EMAIL", valid: false },
{ input: "https://example.com", filter: "FILTER_VALIDATE_URL", valid: true },
{ input: "example.com"
...โ ๏ธ Common Mistakes
htmlspecialchars() to prevent XSS attacks.$_SERVER['REQUEST_METHOD'] === 'POST' before processing.exit; after header('Location: ...') to prevent the rest of the page from executing.๐ Quick Reference โ Forms
| Function | Purpose |
|---|---|
| $_GET / $_POST | Access form data |
| htmlspecialchars() | Prevent XSS (escape HTML) |
| filter_var() | Validate/sanitize specific types |
| trim() / strip_tags() | Clean whitespace/HTML |
| $_SERVER['REQUEST_METHOD'] | Check GET or POST |
๐ Lesson Complete!
You can now handle form data securely! Next, learn how to persist data between pages with sessions and cookies.
Sign up for free to track which lessons you've completed and get learning reminders.