iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Filters

PHP's filter_var() and filter_input() validate and sanitise individual values against named filters. Built-in, no library needed.

Validate

PHP
filter_var('ada@example.com', FILTER_VALIDATE_EMAIL);      // 'ada@example.com'
filter_var('not-an-email',      FILTER_VALIDATE_EMAIL);      // false

filter_var('42', FILTER_VALIDATE_INT);             // 42
filter_var('3.14', FILTER_VALIDATE_FLOAT);          // 3.14
filter_var('on',  FILTER_VALIDATE_BOOL);            // true
filter_var('https://example.com', FILTER_VALIDATE_URL);
filter_var('192.168.1.1', FILTER_VALIDATE_IP);

Each returns the value on success, or false on failure.

With options

PHP
$age = filter_var('25', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 0, 'max_range' => 130],
]);

$id = filter_var($_GET['id'] ?? null, FILTER_VALIDATE_INT, [
    'options' => ['default' => 0, 'min_range' => 1],
]);

Sanitise

PHP
// Strip everything but digits
filter_var('hi 42 there', FILTER_SANITIZE_NUMBER_INT);   // '42'

// Strip everything but URL-safe chars
filter_var($url, FILTER_SANITIZE_URL);

// (Note: FILTER_SANITIZE_STRING was removed in PHP 8.1 — use htmlspecialchars on output.)

Filtering superglobals safely

PHP
$id    = filter_input(INPUT_GET,  'id',    FILTER_VALIDATE_INT);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

What filters DON'T do

  • FILTER_VALIDATE_EMAIL doesn't verify the address receives mail.
  • FILTER_VALIDATE_URL accepts javascript: etc. — check the scheme yourself.
  • None of them protect SQL — use parameter binding for that.
Tip: Validate the shape with filters; enforce meaning with your own checks (does this user exist? Is this product in stock?). Filters are the first layer, not the only one.

Example

Example
<?php
$email = filter_var('ada@example.com', FILTER_VALIDATE_EMAIL);
$int   = filter_var('42abc', FILTER_VALIDATE_INT);
var_dump($email, $int);
Try it Yourself »

Exercise

Validate an int with this function.

($x, FILTER_VALIDATE_INT)

Test yourself

Q1. Validate an int safely with…
Q2. FILTER_SANITIZE_STRING is…
Q3. filter_input reads from…

Discussion

Loading…