Filters in PHP
? Filters in PHP (Validation + Sanitization)
PHP filters are used to validate and sanitize input data — especially helpful when dealing with form data, URLs, cookies, or any external input.
? What Are Filters?
Filters are functions from the filter extension that ensure input is:
? Valid — matches a specific format (e.g., email, integer)
? Sanitized — cleaned from illegal or harmful characters
? 1. Sanitization Filters
These remove or encode unwanted characters.
$name = "<b>John</b>";$clean_name = filter_var($name, FILTER_SANITIZE_STRING); // Deprecated$clean_name = strip_tags($name); // Preferred nowecho $clean_name; // Output: JohnCommon Sanitization Filters:
| Filter Constant | Description |
|---|---|
FILTER_SANITIZE_STRING | Removes tags (deprecated in PHP 8.1+) |
FILTER_SANITIZE_EMAIL | Removes illegal email characters |
FILTER_SANITIZE_URL | Removes illegal URL characters |
FILTER_SANITIZE_NUMBER_INT | Removes everything except digits, +, - |
FILTER_SANITIZE_SPECIAL_CHARS | Encodes HTML special characters |
? 2. Validation Filters
These check if the input is valid (returns the value on success or false on failure).
$email = "user@example.com";if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email!";} else { echo "Invalid email!";}Common Validation Filters:
| Filter Constant | Description |
|---|---|
FILTER_VALIDATE_INT | Validates integer |
FILTER_VALIDATE_FLOAT | Validates floating-point numbers |
FILTER_VALIDATE_EMAIL | Validates email |
FILTER_VALIDATE_URL | Validates URL |
FILTER_VALIDATE_IP | Validates IP (IPv4 or IPv6) |
FILTER_VALIDATE_BOOLEAN | true, false, 1, 0, etc. |
? 3. Validate with Options
$age = 25;$options = ["options" => ["min_range" => 18, "max_range" => 99]];if (filter_var($age, FILTER_VALIDATE_INT, $options)) { echo "Valid age.";} else { echo "Age out of range.";}? 4. Using filter_input()
Safely get and filter input from external sources like GET, POST, COOKIE.
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);if ($email) { echo "Email is valid!";} else { echo "Invalid email.";}? Best Practices
Always sanitize before displaying user input.
Always validate before storing input.
Combine both for maximum safety.