PHP Filters
PHP's filter extension provides a consistent way to validate and sanitize external data such as form input, using the filter_var() function together with predefined filter constants.
Validation filters check whether data matches an expected format (returning false if not), while sanitization filters clean up data by removing or encoding unwanted characters.
filter_var($value, FILTER_VALIDATE_EMAIL);
filter_var($value, FILTER_SANITIZE_FULL_SPECIAL_CHARS);Validation filters
Filters like FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT, and FILTER_VALIDATE_URL check that a value matches the expected format and return false if it doesn't.
Sanitization filters
Filters like FILTER_SANITIZE_FULL_SPECIAL_CHARS or FILTER_SANITIZE_NUMBER_INT clean up a string by removing or encoding characters that don't belong.
<?php
$age = "25";
var_dump(filter_var($age, FILTER_VALIDATE_INT));
?>int(25)FILTER_VALIDATE_INT confirms the string is a valid integer and converts it to an int.
<?php
$url = "not a url";
var_dump(filter_var($url, FILTER_VALIDATE_URL));
?>bool(false)FILTER_VALIDATE_URL returns false because the given string is not a valid URL.
Key points
- filter_var() applies a validation or sanitization filter to a value.
- Validation filters return false when data doesn't match the expected format.
- Sanitization filters clean data by removing or encoding unwanted characters.
- Filters are a consistent, built-in way to handle untrusted input.
