What is it?
HTML forms are the primary way users send data to a PHP server. PHP reads that data through superglobals ($_GET, $_POST) and must validate and sanitize it before use.
Why does it matter?
Forms are the entry point for all user-generated data — and therefore the entry point for attacks. Every field is a potential SQL injection or XSS vector if not handled correctly.
Learn PHP form handling — GET vs POST, reading $_POST data, validation, and sanitization.
Real-World Use Cases
- 🔑 Login form - Read username and password from $_POST, validate they are not empty, then verify against the database.
- 📝 Contact form - Collect name, email, and message via POST, validate each field, then send an email to the admin.
- 🔍 Search box - Read a search query from $_GET, sanitize it, use it in a LIKE query, and display results.
- 🛒 Add to cart - Read product_id and quantity from a POST form, validate they are positive integers, then update the cart session.
Reading Form Data
// process.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
echo "Name: $username, Email: $email";
}
Sanitize and Validate — Always!
// --------------------
// SANITIZE INPUT
// --------------------
// Remove unwanted characters
$username = htmlspecialchars(trim($username));
$email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);
GET vs POST
<?php
/*
--------------------------------
GET vs POST Example
--------------------------------
*/
// ---------------- GET ----------------
// URL Example:
// test.php?city=Pune
$city = $_GET['city'] ?? '';
if (!empty($city)) {
$city = htmlspecialchars(trim($city));
echo "<h3>GET Method</h3>";
echo "City: " . $city . "<br><br>";
}
// ---------------- POST ----------------
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'] ?? '';
// Sanitize
$name = htmlspecialchars(trim($name));
echo "<h3>POST Method</h3>";
echo "Name: " . $name;
}
?>
<!-- POST FORM -->
<form method="POST">
<input type="text" name="name" placeholder="Enter Name">
<button type="submit">Submit</button>
</form>
<!--
--------------------------------
GET vs POST Summary
--------------------------------
GET
- Data visible in URL
- Less secure
- Used for search/filter
POST
- Data hidden from URL
- More secure
- Used for login/forms
--------------------------------
-->
Q: What is XSS and how does htmlspecialchars() prevent it?
XSS is when attackers inject JavaScript via form fields. htmlspecialchars() converts < and > into safe HTML entities so scripts never execute. Always apply before displaying user input in HTML.
Comments (0)
No comments yet. Be the first!
Leave a Comment