Introduction
Input validation and sanitization help keep your program safe and working well by checking and cleaning user data.
Input validation and sanitization help keep your program safe and working well by checking and cleaning user data.
<?php // Validate input if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // Input is a valid email } // Sanitize input $clean_name = strip_tags($name); ?>
Use filter_var() to check or clean data.
Validation checks if data is correct; sanitization cleans unwanted parts.
<?php $email = "user@example.com"; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email."; } else { echo "Invalid email."; } ?>
<?php $name = "John <b>Doe</b>"; $clean_name = strip_tags($name); echo $clean_name; ?>
<?php $age = "25 years"; $clean_age = filter_var($age, FILTER_SANITIZE_NUMBER_INT); echo $clean_age; ?>
This program checks if the email is valid and cleans the name to remove harmful code.
<?php // Sample program to validate and sanitize user input $user_email = "test@example.com"; $user_name = "Alice <script>alert('x');</script>"; // Validate email if (filter_var($user_email, FILTER_VALIDATE_EMAIL)) { echo "Email is valid.\n"; } else { echo "Email is invalid.\n"; } // Sanitize name $safe_name = strip_tags($user_name); echo "Sanitized name: " . $safe_name . "\n"; ?>
Always validate before sanitizing to catch bad data early.
Sanitization helps prevent security problems like code injection.
Use the right filter for the type of data you expect.
Input validation checks if data is correct and safe.
Sanitization cleans data by removing unwanted parts.
Use PHP's filter_var() function for both tasks.
$input = ""; $clean = filter_var($input, FILTER_SANITIZE_STRING); echo $clean;
$age = $_POST['age'];
if (filter_var($age, FILTER_SANITIZE_INT)) {
echo "Valid age";
} else {
echo "Invalid age";
}filter_var() and a custom pattern?Pass the test and this pattern moves unknown