Imagine youโre building a login form or an email signup system. What if users enter garbage data? Or worseโtry to hack your site with SQL injections or XSS attacks? ๐ฑ Thatโs why validating and sanitizing user input is critical in PHP!
In this step-by-step guide, weโll explore how to clean, validate, and secure user input with real-world examples and a mini-project at the end. ๐ฏ
๐ฏ Why Input Validation Matters
๐ก Never trust user input!
If your site accepts user input, you must validate and sanitize it before storing or processing it.
โ What Can Go Wrong?
Issue | Example | Risk |
---|---|---|
SQL Injection | ' OR 1=1 -- |
Hackers can delete your database |
XSS Attack | <script>alert('Hacked!')</script> |
JavaScript can steal user data |
Invalid Email | zeroexp.dev@example |
Fake accounts and spam |
Empty Fields | "" (blank) |
Leads to broken functionality |
๐ฅ Solution? Always use validation + sanitization!
1๏ธโฃ Sanitizing Input Data in PHP
Sanitization cleans user input so it canโt harm your site.
Example: Cleaning User Input
<?php
$name = "<script>alert('Hacked!')</script>";
$clean_name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo $clean_name; // Output: <script>alert('Hacked!')</script>
?>
๐ฅ Why? htmlspecialchars()
escapes special characters, preventing XSS attacks.
2๏ธโฃ Validating Text Input
Example: Checking for Empty Fields
<?php
$name = trim($_POST['name'] ?? '');
if (empty($name)) {
echo "Name is required!";
} else {
echo "Hello, $name!";
}
?>
๐ฅ Why? trim()
removes unnecessary spaces, and empty()
ensures a value is entered.
Example: Allowing Only Letters
<?php
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
echo "Only letters and spaces allowed!";
}
?>
๐ฅ Why? This prevents numbers and symbols in names.
3๏ธโฃ Validating Email Addresses
Example: Checking Email Format
<?php
$email = $_POST['email'] ?? '';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format!";
} else {
echo "Email is valid!";
}
?>
๐ฅ Why? FILTER_VALIDATE_EMAIL
automatically rejects invalid emails.
4๏ธโฃ Validating Numbers
Example: Checking for a Valid Age
<?php
$age = $_POST['age'] ?? '';
if (!filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 18, "max_range" => 100]])) {
echo "Age must be between 18 and 100!";
} else {
echo "Valid age!";
}
?>
๐ฅ Why? FILTER_VALIDATE_INT
ensures it's a number between 18 and 100.
5๏ธโฃ Preventing SQL Injection
Example: Secure Database Insertion
<?php
$conn = new mysqli("localhost", "root", "", "zeroexp_dev");
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['name'], $_POST['email']);
$stmt->execute();
?>
๐ฅ Why? Prepared statements prevent SQL injection attacks!
6๏ธโฃ Preventing XSS Attacks
Example: Escaping Output
<?php
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
echo "Hello, $name!";
?>
๐ฅ Why? Prevents scripts from running in the browser.
๐ฏ Mini Project: Secure Contact Form
Letโs build a real-world contact form that validates and sanitizes input before processing.
contact.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');
$errors = [];
// Validate Name
if (empty($name) || !preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$errors[] = "Valid name is required!";
}
// Validate Email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required!";
}
// Validate Message
if (empty($message)) {
$errors[] = "Message cannot be empty!";
}
if (empty($errors)) {
echo "Thank you, $name! Your message has been sent.";
} else {
foreach ($errors as $error) {
echo "<p style='color:red'>$error</p>";
}
}
}
?>
<form method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" value="Send">
</form>
๐ฅ Why?
- Validates required fields
- Checks email format
- Displays error messages instead of letting bad data through
๐ Final Thoughts
Now, you know how to protect your PHP forms! You can: โ
Sanitize input to remove harmful characters
โ
Validate text, emails, and numbers
โ
Prevent SQL injection using prepared statements
โ
Stop XSS attacks with htmlspecialchars()
๐ Next: PHP Sessions and Cookies
Happy coding! ๐๐
Always make sure to add form validations.