🎒 PHP Form Handling: The Magical Post Office
Imagine a post office where people send letters (data) to you. Your job is to receive those letters safely, check if they’re real, and make sure no sneaky tricks are hidden inside!
🌟 The Big Picture
When someone fills out a form on a website (like their name or email), that information travels to your PHP server. Think of it like:
- The User = Someone writing a letter
- The Form = The envelope
- PHP = The post office worker who receives and checks everything
📮 GET Request Processing
What Is It?
GET is like sending a postcard. Everyone can see what’s written on it!
When you type www.shop.com/search?item=toys in your browser, the ?item=toys part is visible to everyone. It’s attached right to the address.
Simple Example
// Someone visits: shop.php?product=teddy
$product = $_GET['product'];
echo "You searched for: " . $product;
// Output: You searched for: teddy
When to Use GET?
- ✅ Searching for something
- ✅ Filtering a list
- ✅ Sharing a link with data
- ❌ NOT for passwords or secrets!
Real Life
When you search on Google, your search words appear in the URL. That’s GET in action!
📦 POST Request Processing
What Is It?
POST is like sending a sealed package. The contents are hidden inside, not visible in the URL.
When you submit a login form with your password, POST keeps it hidden from the address bar.
Simple Example
// A login form sends data via POST
$username = $_POST['username'];
$password = $_POST['password'];
echo "Welcome, " . $username;
GET vs POST - Quick Compare
| Feature | GET (Postcard) | POST (Package) |
|---|---|---|
| Visible in URL? | Yes | No |
| Safe for secrets? | No | Yes |
| Bookmark-able? | Yes | No |
| Data limit? | ~2000 chars | Large files OK |
✅ Form Validation Basics
What Is It?
Validation = Checking if the letter makes sense before you accept it.
Like a teacher checking if homework has a name on it!
Simple Example
$email = $_POST['email'];
// Check: Is it empty?
if (empty($email)) {
echo "Please enter your email!";
}
// Check: Does it look like an email?
if (strpos($email, '@') === false) {
echo "That doesn't look like an email!";
}
Common Checks
- 📝 Required fields - Is it empty?
- 📏 Length - Too short? Too long?
- 🔢 Numbers only - Is it actually a number?
- 📧 Email format - Has @ symbol?
🧹 Input Sanitization
What Is It?
Sanitization = Cleaning the letter before reading it.
Imagine someone sent you a letter with glitter bomb inside! You need to safely remove the dangerous stuff before opening it.
The Danger
Bad people might send sneaky code like:
<script>steal_cookies()</script>
If you display this on your page, bad things happen!
Simple Example
$name = $_POST['name'];
// DANGEROUS - displays anything!
echo $name;
// SAFE - removes bad stuff
$clean_name = htmlspecialchars($name);
echo $clean_name;
What htmlspecialchars Does
| Dangerous Input | Cleaned Output |
|---|---|
<script> |
<script> |
"onclick=" |
"onclick=" |
Now the sneaky code is just harmless text!
🔍 filter_var Function
What Is It?
filter_var is like a magical magnifying glass that can both check AND clean data in one go!
Simple Examples
$email = "john@example.com";
$age = "25";
$dirty = "<script>bad</script>";
// VALIDATE: Is this a real email?
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email!";
}
// VALIDATE: Is this a number?
if (filter_var($age, FILTER_VALIDATE_INT)) {
echo "Valid number!";
}
// SANITIZE: Clean this string
$clean = filter_var($dirty, FILTER_SANITIZE_SPECIAL_CHARS);
// Result: <script>bad</script>
Common Filters
| Filter | Purpose |
|---|---|
FILTER_VALIDATE_EMAIL |
Check email format |
FILTER_VALIDATE_INT |
Check if number |
FILTER_VALIDATE_URL |
Check URL format |
FILTER_SANITIZE_SPECIAL_CHARS |
Clean dangerous characters |
FILTER_SANITIZE_NUMBER_INT |
Keep only numbers |
🎯 filter_input Function
What Is It?
filter_input is filter_var’s smarter sibling! It grabs data directly from GET or POST AND filters it in one step.
Simple Example
// OLD WAY (2 steps)
$email = $_POST['email'];
$clean = filter_var($email, FILTER_SANITIZE_EMAIL);
// NEW WAY (1 step!)
$clean = filter_input(
INPUT_POST,
'email',
FILTER_SANITIZE_EMAIL
);
The Three Parts
filter_input(WHERE, WHAT, HOW)
// WHERE = INPUT_GET or INPUT_POST
// WHAT = the field name
// HOW = the filter to apply
Complete Example
// Get and validate age from form
$age = filter_input(
INPUT_POST,
'age',
FILTER_VALIDATE_INT
);
if ($age === false) {
echo "Please enter a valid number!";
} elseif ($age === null) {
echo "Age field is missing!";
} else {
echo "Your age: $age";
}
🛡️ CSRF Protection
What Is It?
CSRF = Cross-Site Request Forgery
Imagine a bad guy makes your friend send a letter pretending to be you! CSRF protection is like a secret handshake that proves the letter really came from your friend.
The Danger
Without protection:
- You’re logged into your bank
- You visit a bad website
- That site secretly submits a “transfer money” form to your bank
- Your bank thinks YOU sent it!
The Solution: Tokens
A token is a secret code that only your form knows.
graph TD A["Your Page Loads"] --> B["Generate Secret Token"] B --> C["Hide Token in Form"] C --> D["User Submits Form"] D --> E{Token Match?} E -->|Yes| F["Process Form ✅"] E -->|No| G["Reject! 🚫"]
Simple Example
Step 1: Create the token
session_start();
// Generate random secret
$token = bin2hex(random_bytes(32));
// Save it in session
$_SESSION['csrf_token'] = $token;
Step 2: Add to form
<form method="POST">
<input type="hidden"
name="csrf_token"
value="<?php echo $token; ?>">
<input type="text" name="email">
<button>Submit</button>
</form>
Step 3: Verify on submit
session_start();
$submitted = $_POST['csrf_token'];
$stored = $_SESSION['csrf_token'];
if ($submitted !== $stored) {
die("CSRF attack detected!");
}
// Safe to process form
echo "Form accepted!";
🎯 Putting It All Together
Here’s a complete, safe form handler:
<?php
session_start();
// Generate CSRF token for form
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$_SESSION['csrf_token'] = bin2hex(
random_bytes(32)
);
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 1. CSRF Check
$token = $_POST['csrf_token'] ?? '';
if ($token !== $_SESSION['csrf_token']) {
die("Security error!");
}
// 2. Get & Sanitize
$email = filter_input(
INPUT_POST,
'email',
FILTER_SANITIZE_EMAIL
);
// 3. Validate
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email!";
} else {
echo "Welcome, $email!";
}
}
?>
🌈 Summary: Your Safety Checklist
| Step | What | Why |
|---|---|---|
| 1 | Use POST for secrets | Hides data from URL |
| 2 | Validate input | Check if data is correct |
| 3 | Sanitize input | Remove dangerous code |
| 4 | Use filter functions | Built-in safety tools |
| 5 | Add CSRF tokens | Prevent fake requests |
🚀 You’re Ready!
You now know how to:
- ✅ Handle GET and POST requests
- ✅ Validate that data is correct
- ✅ Sanitize to remove dangers
- ✅ Use
filter_varandfilter_input - ✅ Protect against CSRF attacks
Your forms are now like a fortress! 🏰
Every letter that arrives gets checked, cleaned, and verified before you trust it. Bad guys don’t stand a chance!
