TExcelTAD
Home › PHP › PHP Filters

PHP Filters

Every value from outside your program — form fields, query strings, cookies, API payloads — arrives as an untrusted string. PHP's filter extension gives you ready-made, well-tested checks for the most common formats: integers, floats, booleans, email addresses, URLs and IP addresses. One function does almost all the work: filter_var().

Validate vs sanitize

Filters come in two flavours:

Kind What it does On bad input
Validate (FILTER_VALIDATE_*) Checks the value and converts it to the right type Returns false (or null with FILTER_NULL_ON_FAILURE)
Sanitize (FILTER_SANITIZE_*) Removes unwanted characters Always returns a (cleaned) string

Prefer validation: rejecting bad data and asking the user to fix it is safer than silently changing it.

Validating numbers

php · try it yourself
<?php
$inputs = ['42', ' 7 ', '3.5', '0x1A', 'abc', '-0'];

foreach ($inputs as $in) {
    $result = filter_var($in, FILTER_VALIDATE_INT);
    printf("%-7s => %s\n", var_export($in, true), var_export($result, true));
}

echo "--- with a range ---" . PHP_EOL;
$opts = ['options' => ['min_range' => 1, 'max_range' => 10]];
var_dump(filter_var('5', FILTER_VALIDATE_INT, $opts));
var_dump(filter_var('11', FILTER_VALIDATE_INT, $opts));

echo "--- hex allowed by flag ---" . PHP_EOL;
var_dump(filter_var('0x1A', FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX));
'42'    => 42
' 7 '   => 7
'3.5'   => false
'0x1A'  => false
'abc'   => false
'-0'    => 0
--- with a range ---
int(5)
bool(false)
--- hex allowed by flag ---
int(26)

Notice that a valid value comes back as a real int, and surrounding whitespace is tolerated.

Tip: Compare the result with === false. A valid input of "0" returns 0, which is falsy, so if (!filter_var(...)) would wrongly reject it.

Floats and booleans

FILTER_VALIDATE_FLOAT accepts decimal numbers (optionally with a custom decimal separator). FILTER_VALIDATE_BOOL understands the words people actually put in checkboxes and config files:

php · try it yourself
<?php
var_dump(filter_var('19.99', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('19,99', FILTER_VALIDATE_FLOAT, ['options' => ['decimal' => ',']]));
var_dump(filter_var('1e3', FILTER_VALIDATE_FLOAT));

echo "--- booleans ---" . PHP_EOL;
foreach (['yes', 'on', '1', 'true', 'no', 'off', '0', '', 'maybe'] as $v) {
    $b = filter_var($v, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE);
    echo str_pad("'$v'", 8) . " => " . var_export($b, true) . PHP_EOL;
}
float(19.99)
float(19.99)
float(1000)
--- booleans ---
'yes'    => true
'on'     => true
'1'      => true
'true'   => true
'no'     => false
'off'    => false
'0'      => false
''       => false
'maybe'  => NULL

With FILTER_NULL_ON_FAILURE, "not a boolean at all" (null) is distinguishable from "a valid false" (false).

Email, URL and IP addresses

php · try it yourself
<?php
$checks = [
    ['an@example.test', FILTER_VALIDATE_EMAIL],
    ['an@@example', FILTER_VALIDATE_EMAIL],
    ['https://example.test/docs?page=2', FILTER_VALIDATE_URL],
    ['example.test', FILTER_VALIDATE_URL],
    ['192.168.1.20', FILTER_VALIDATE_IP],
    ['300.1.1.1', FILTER_VALIDATE_IP],
    ['::1', FILTER_VALIDATE_IP],
];

foreach ($checks as [$value, $filter]) {
    $ok = filter_var($value, $filter) !== false;
    echo str_pad($value, 34) . ($ok ? 'valid' : 'INVALID') . PHP_EOL;
}

// Flags narrow the check further
var_dump(filter_var('::1', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4));
var_dump(filter_var('192.168.1.20', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
an@example.test                   valid
an@@example                       INVALID
https://example.test/docs?page=2  valid
example.test                      INVALID
192.168.1.20                      valid
300.1.1.1                         INVALID
::1                               valid
bool(false)
bool(false)

Note: FILTER_VALIDATE_URL accepts any scheme, including javascript:. If you will put a URL in a link, also check that it starts with http:// or https://.

Sanitizing

Sanitize filters strip characters. They are handy for normalising input that you will validate afterwards:

php · try it yourself
<?php
$phone = '+84 (0)912-345-678';
echo filter_var($phone, FILTER_SANITIZE_NUMBER_INT) . PHP_EOL;

$price = 'USD 1,299.50';
echo filter_var($price, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) . PHP_EOL;

$email = ' (an)@exa mple.test ';
echo filter_var($email, FILTER_SANITIZE_EMAIL) . PHP_EOL;

echo filter_var('<b>Hi</b> & "you"', FILTER_SANITIZE_SPECIAL_CHARS) . PHP_EOL;
+840912-345-678
1299.50
an@example.test
&#60;b&#62;Hi&#60;/b&#62; &#38; &#34;you&#34;

The old FILTER_SANITIZE_STRING was removed in PHP 8.1 — use htmlspecialchars() when printing instead.

Filtering many fields at once

filter_var_array() applies a whole set of rules to an array such as $_POST. Missing keys become null, invalid ones false:

php · try it yourself
<?php
$_POST = ['age' => '34', 'email' => 'not-an-email', 'newsletter' => 'on'];

$rules = [
    'age'        => ['filter' => FILTER_VALIDATE_INT, 'options' => ['min_range' => 0]],
    'email'      => FILTER_VALIDATE_EMAIL,
    'newsletter' => FILTER_VALIDATE_BOOL,
    'country'    => FILTER_DEFAULT,
];

var_dump(filter_var_array($_POST, $rules));
array(4) {
  ["age"]=>
  int(34)
  ["email"]=>
  bool(false)
  ["newsletter"]=>
  bool(true)
  ["country"]=>
  NULL
}

On a real server, filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT) reads directly from the original request data instead of $_POST.

Test yourself

What does filter_var('0', FILTER_VALIDATE_INT) return?

  1. false
  2. '0'
  3. 0
  4. null

Which filter type always returns a string with unwanted characters removed?

  1. Validate filters
  2. Sanitize filters
  3. Callback filters
  4. Boolean filters

How do you restrict FILTER_VALIDATE_INT to 1–10?

  1. FILTER_FLAG_RANGE_10
  2. ['options' => ['min_range' => 1, 'max_range' => 10]]
  3. ['min' => 1, 'max' => 10]
  4. It isn't possible