Open In App

PHP | filter_input() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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 hold 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
// 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




<?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



Last Updated : 29 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads