PHP ยท Chapter 33 of 44

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.

Syntax
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.

Example 1 (php)
<?php
  $age = "25";
  var_dump(filter_var($age, FILTER_VALIDATE_INT));
?>
Output
int(25)

FILTER_VALIDATE_INT confirms the string is a valid integer and converts it to an int.

Example 2 (php)
<?php
  $url = "not a url";
  var_dump(filter_var($url, FILTER_VALIDATE_URL));
?>
Output
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.
๐Ÿ’ก Note: Always check filter_var()'s return value against false with === to correctly detect invalid input like "0".

๐Ÿ“ Quick Quiz

1. What does filter_var() with FILTER_VALIDATE_EMAIL return for invalid input?

2. What is the purpose of a sanitization filter?

3. Which function applies PHP's built-in filters?