PHP Filters Advanced

In PHP, filters are primarily used for validating and sanitizing external input. The filter_var() and filter_input() functions from the Filter extension are central to this feature.

Let’s look at some advanced uses of PHP filters:


1. Advanced Validation with filter_var()

Example: Validate IP Address (IPv4 & IPv6)

$ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { echo "Valid IPv6"; }

Validate URL with query string

$url = "https://example.com?foo=bar"; if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)) { echo "URL with query string is valid."; }

2. Sanitization with Custom Flags

Strip high ASCII characters from a string

$str = "Hello™"; $clean = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); echo $clean; // Outputs: Hello

3. Using filter_input() for Secure Input Handling

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); if ($email === false) { echo "Invalid email!"; }

4. filter_var_array() and filter_input_array()

Validate multiple fields at once

$data = [ 'email' => 'user@example.com', 'age' => '29' ]; $args = [ 'email' => FILTER_VALIDATE_EMAIL, 'age' => [ 'filter' => FILTER_VALIDATE_INT, 'options' => ['min_range' => 18, 'max_range' => 99] ] ]; $result = filter_var_array($data, $args); print_r($result);

5. Custom Callbacks with FILTER_CALLBACK

function sanitize_name($name) { return ucwords(strtolower(trim($name))); } $name = " jOHN DOE "; $clean = filter_var($name, FILTER_CALLBACK, [ 'options' => 'sanitize_name' ]); echo $clean; // Outputs: John Doe

6. Using with Forms and Security Best Practices

  • Always validate and sanitize all user input, especially from $_GET, $_POST, and $_COOKIE.

  • Use filter_input_array() in form processing to clean data in bulk.

  • Use filters in combination with prepared statements for database input.