R
Rishtaara
PHP Fundamentals
Lesson 18 of 32Article17 min

Filters & Advanced Filters

filter_var() validates emails, URLs, IPs, and integers. filter_input() reads superglobals safely.

PHP Filters — validate and sanitize

filter_var() validates emails, URLs, IPs, and integers. filter_input() reads superglobals safely.

Real-life example: Filters are water purifiers — dirty input goes in, cleaner data comes out.

Validate with filters
<?php
$email = "test@example.com";
$age = "25";

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  die("Bad email");
}

$age = filter_var($age, FILTER_VALIDATE_INT, [
  "options" => ["min_range" => 1, "max_range" => 120],
]);
?>

Sanitize filters

FILTER_SANITIZE_STRING (deprecated in PHP 8.1+) — use htmlspecialchars for output. FILTER_SANITIZE_EMAIL and FILTER_SANITIZE_URL clean input.

Real-life example: Sanitizing is trimming sharp edges off a toy before giving it to a child.

Sanitize examples
<?php
$dirty = "  Hello<script>alert(1)</script>  ";
$clean = htmlspecialchars(strip_tags(trim($dirty)), ENT_QUOTES, "UTF-8");
echo $clean;

$url = filter_var("https://knowvora.com/?x=1", FILTER_SANITIZE_URL);
echo $url;
?>

Advanced filters — filter_list and custom options

filter_list() shows all filter IDs. filter_has_var() checks if input exists. Combine filters with flags like FILTER_FLAG_IPV4.

Real-life example: filter_list is reading every tool name on a Swiss Army knife before picking the right blade.

Advanced filter usage
<?php
// Check if GET param exists and is valid int
if (filter_has_var(INPUT_GET, "id")) {
  $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
  if ($id !== false && $id !== null) {
    echo "Course ID: $id";
  }
}

$ip = filter_var("192.168.1.1", FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
var_dump($ip);
?>