Skip to content
Related Articles

Related Articles

Improve Article

PHP | filter_input() Function

  • Last Updated : 14 Feb, 2019

The filter_input() is an inbuilt function in PHP which is used to get the specific external variable by name and filter it. This function is used to validate variables from insecure sources, such as user input from form. This function is very much useful to prevent some potential security threat like SQL Injection.

Syntax:

filter_input( $type, $variable_name, $filter, $options)

Parameters: This function accepts four parameters as mentioned above and described below:

  • $type: It is mandatory parameter and used to check the type of input. The list of filters are:
    • INPUT_GET
    • INPUT_POST
    • INPUT_COOKIE
    • INPUT_SERVER
    • INPUT_ENV
  • $variable_name: It is required parameter. It is used to hols the name of variable which is to be checked.
  • $filter: It is an optional parameter. It holds the name or ID of the filter. If this parameter is not set then FILTER_DEFAULT is used.
  • $options: It is an optional parameter and used to specify one or more flags/options to use. It check for possible options and flags in each filter. If filter options are accepted then flags can be provided in “flags” field of array.

Return Value: It returns the value of the variable on success or False on failure. If parameter is not set then return NULL. 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 1:






<?php
// PHP program to validate email using filter
  
if (isset($_GET["email"])) {
    if (!filter_input(INPUT_GET, "email"
            FILTER_VALIDATE_EMAIL) === false) {
        echo("Valid Email");
    } else {
        echo("Invalid Email");
    }
}
  
?>

Output:

Valid Email

Example 2:




<?php
  
// Input type:INPUT_GET input name:search 
// filter name:FILTER_SANITIZE_SPECIAL_CHARS
$search_variable_data = filter_input(INPUT_GET, 
            'search', FILTER_SANITIZE_SPECIAL_CHARS);
              
// Input type:INPUT_GET input name:search
// filter name:FILTER_SANITIZE_ENCODED
$search_url_data = filter_input(INPUT_GET,
            'search', FILTER_SANITIZE_ENCODED);
              
echo "Search for $search_variable_data.\n";
  
echo "<a href='?search=$search_url_data'>Search again.</a>";
  
?>

Output:

Search for tic tac & toc. Search again.

References: http://php.net/manual/en/function.filter-input.php




My Personal Notes arrow_drop_up
Recommended Articles
Page :