PHP Filters
Validating data = Determine if the data is in the proper form. Sanitizing data = Remove any illegal character from the data.
PHP filters are used to validate and sanitize external input.
1. The filter_var() Function
The filter_var() function both validates and sanitizes data. It takes two arguments: the variable you want to check, and the type of check to use.
2. Validating Data
Validation filters are used to validate user input.
FILTER_VALIDATE_EMAIL: Checks if the variable is a valid email address.FILTER_VALIDATE_INT: Checks if the variable is an integer.FILTER_VALIDATE_IP: Checks if the variable is a valid IP address.FILTER_VALIDATE_URL: Checks if the variable is a valid URL.
$email = "john.doe@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is a valid email address";
} else {
echo "$email is NOT a valid email address";
}
3. Sanitizing Data
Sanitization filters are used to allow or remove specified characters.
FILTER_SANITIZE_EMAIL: Removes all illegal characters from an email address.FILTER_SANITIZE_URL: Removes all illegal characters from a URL.
$email = "john(.doe)@exa//mple.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $email; // Outputs: john.doe@example.com
4. Filter Input
The filter_input() function gets an external variable (e.g. from form input) and optionally filters it.
// Check if "email" is sent via GET and is valid
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
echo "Email is not valid";
} else {
echo "Email is valid";
}