Sanitize and Validate User Input in PHP
Improve security by learning to sanitize and validate all user input in PHP using filters and best practices.
๐ Why Sanitize and Validate Input?
User input is one of the most common attack vectors for web applications. To protect your PHP apps from XSS, SQL injection, and other vulnerabilities, it's essential to sanitize and validate all incoming data.
๐งผ Sanitizing Input
Sanitizing removes unwanted characters or HTML from the input to ensure it's safe to process.
Examples:
<?php
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$url = filter_var($_POST['website'], FILTER_SANITIZE_URL);
?>
Use these filters to prevent users from injecting scripts, broken markup, or malformed data.
โ๏ธ Validating Input
Validation checks whether the input matches an expected format or type.
Examples:
<?php
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL";
}
?>
๐ Custom Validation with Regex
<?php
$username = $_POST['username'];
if (preg_match("/^[a-zA-Z0-9_]{3,20}$/", $username)) {
echo "Valid username";
} else {
echo "Username must be 3-20 characters and alphanumeric.";
}
?>
โ Best Practices
- Never trust client-side validation alone
- Use
htmlspecialchars()
before outputting user data - Validate data type, length, and structure
- Use a central validation function or library for consistency
๐ Full Example
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email');
}
echo "Hello, " . htmlspecialchars($name);
}
?>