Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

filter_var

Validates or sanitises a value by a given rule.

Syntax

filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

Parameters

ParameterTypeDescription
$valuemixedThe value to check.
$filterintThe rule: `FILTER_VALIDATE_EMAIL`, `FILTER_VALIDATE_INT`, `FILTER_VALIDATE_URL` and others.
$optionsarray|intOptional. Extra settings such as number bounds.

Return value

mixedThe validated value, or `false` if it did not pass.

Examples

An email and an integer:

<?php
 
var_dump(filter_var('anna@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('not-an-email', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('42', FILTER_VALIDATE_INT));

Output:

string(16) "anna@example.com"
bool(false)
int(42)

A number within bounds:

<?php
 
$options = ['options' => ['min_range' => 1, 'max_range' => 120]];
 
var_dump(filter_var('25', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('500', FILTER_VALIDATE_INT, $options));

Output:

int(25)
bool(false)

Notes

On success the value itself is returned, already of the right type. Compare the result with false strictly: the number 0 is a valid result.

See also

  • is_numeric — Checks whether a value is a number or a numeric string.
  • htmlspecialchars — Replaces HTML special characters with safe entities.
  • intval — Converts a value to an integer.

Related recipes

In the tutorial

  • Security — The basics of PHP site security — XSS and escaping, SQL injection, password hashing, CSRF tokens and validating input.

Thanks for reading!

Donate to the site — we work hard for you.