PHP Function Reference

PHP filter_input() Function



The PHP filter_input() function gets a specific external variable by name and optionally filters it.

Syntax

filter_input(type, var_name, filter, options)

Parameters

type Required. Specify the input type. It can be one of the following:
  • INPUT_GET
  • INPUT_POST
  • INPUT_COOKIE
  • INPUT_SERVER
  • INPUT_ENV
var_name Required. Specify the variable name to check.
filter Optional. Specify the ID of the filter to apply. See the filter list. If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.
options Optional. Specify an associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array.

Return Value

Returns the value of the variable on success, false if the filter fails, or null if the var_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns false if the variable is not set and null if the filter fails.

Example: validating an email address

In the example below, filter_input() function is used to validate an email.

<?php
//validating email using filter
if (isset($_GET["email"])) {
  if (!filter_input(INPUT_GET, "email", 
                    FILTER_VALIDATE_EMAIL) === false) {
    echo("Email is valid");
  } else {
    echo("Email is not valid");
  }
}
?>

The output of the above code will be:

Email is valid

Example: a filter_input() example

In the example below, filter_input() function is used to sanitize the given variable.

<?php
//input type: INPUT_GET, input name: search 
//filter name: FILTER_SANITIZE_SPECIAL_CHARS
$search_html = filter_input(INPUT_GET, 'search', 
                            FILTER_SANITIZE_SPECIAL_CHARS);

//input type: INPUT_GET, input name: search
//filter name: FILTER_SANITIZE_ENCODED
$search_url = filter_input(INPUT_GET, 'search', 
                           FILTER_SANITIZE_ENCODED);

echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

The output of the above code will be similar to:

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

❮ PHP Filter Reference