PHP Filters

In this PHP tutorial, you will learn all about the different types of Filters in PHP. We will discuss in detail the types of filters and various types of Filter Functions.

What is meant by Filters in PHP?

PHP Filter is a data filtering extension that either sanities or validates data. It is essential for a website's security, especially when the data comes from unknown or foreign sources, such as user-supplied information. For example, data from an HTML form.

Different types of filters in PHP

  •     Validation
  •     Sanitization

What is a Validation filter in PHP?

Validation is used to determine whether the data fulfills particular criteria or not. For example, using the FILTE_VALIDATE_EMAIL will check if the given data is a valid email or not, and by using the validation it won't affect the specified data.

What is a Sanitization filter in PHP?

Sanitization is not the same as validation, sanitization will sanitize the given data to guarantee that there are no unwanted characters exists by eliminating or changing the data. For example, using the FILTER_SANITIZE_URL will eliminate all characters that are unsuitable for an URL address. However, it does not validate the data.

What all are the different functions used to filter data in PHP

By using the filter function, data from the insecure source can be filtered.

  1.    filter_var(): It is used to filter the variable with the specified filter

    Syntax

    
    filter_var(var, filtername, options)
    
    

    Example

    
        <?php
        $email = "roy@test.com";
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo ("$email is a valid email address");
        } else {
            echo ("$email is not a valid email address");
        }
        ?>
    
    

    Output:

    
    roy@test.com is a valid email address
    
  2.    filter_var_array(): It is used to filter multiple variables mostly the array of variable

    Syntax

    
    filter_var_array(data_array, args, add_empty)
    
    

    Example

    
    <?php
    $details = array(
        'username' =--> 'johndoe',
        'age' => '23',
        'email' => 'johndoe@test.com',
    );
    $filtere_data = filter_var_array($details);
    var_dump($filtere_data);    
    ?>
    
    

    Output:

    
    array(3) {
      ["username"]=>
      string(7) "johndoe"
      ["age"]=>
      string(2) "23"
      ["email"]=>
      string(16) "johndoe@test.com"
    }
    
  3.    filter_has_var(): It is used to check whether a variable of a specified input type exists or not

    Syntax

    
    filter_has_var(type, variable)
    
    

    Example

    
    <?php
    if (!filter_has_var(INPUT_GET, "email")) {
        echo ("Email is available...");
    } else {
        echo ("Email is not available...");
    }
    ?>
    
    

    Output:

    
    Email is not available...
    

    In the above example, the values passed from the form through the get method are checked. The input type to check for. Can be as follows:

  •  INPUT_GET
  •  INPUT_POST
  •  INPUT_COOKIE
  •  INPUT_SERVER
  •  INPUT_ENV 
     
  1.    filter_id(): It is used to return the specific filter id of the given filter name

    Syntax

    
    filter_id(filter_name)
    
    

    Example

    
    <?php
    echo (filter_id("validate_url"));
    echo "\n";
    echo (filter_id("validate_email"));
    ?>
    
    

    Output:

    
    273
    274
    
  2.    filter_list(): It is used to return all the supported filter name

    Syntax

    
    filter_list()
    
    

    Example

    
    <?php
    print_r(filter_list());
    ?>
    
    

    Output:

    
    PHP - Filter
    
  3.    filter_input(): It is used to access an external variable and filter it

    Syntax

    
    filter_input(type, variable, filter, options)
    
    

    Example

    
    !DOCTYPE html>
    <html>
    <body><
        <form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
            E-mail: <input type="text" name="email">
            <input type="submit" name="submit" value="Submit">
        </form>
        <?php
        if (isset($_GET["email"])) {
            if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) === false) {
                echo ("The email is valid");
            } else {
                echo ("The email is not valid");
            }
        }
        ?>
    </body>
    </html>
    
    
    

    Output:

    
    PHP - Filter
    
  4.    filter_input_array(): It is used to access multiple external variables and filter it

    Syntax

    
    filter_input_array(type, definition, add_empty)
    
    

    Example

    
    <html>
    <body>
        <form method="post" action=" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> ">
            Name: <input type="text" name="name">
            Age: <input type="text" name="age">
            E-mail: <input type="text" name="email">
            <input type="submit" name="submit" value="Submit">
        </form>
        <?php
    $filters = array(
            "name" => array(
                "filter" => FILTER_CALLBACK,
                "flags" => FILTER_FORCE_ARRAY,
                "options" => "ucwords"
            ),
            "age"   => array(
                "filter" => FILTER_VALIDATE_INT,
                "options" => array("min_range" => 1, "max_range" => 120)
            ),
            "email" => FILTER_VALIDATE_EMAIL
        );
        print_r(filter_input_array(INPUT_POST, $filters));
        ?>
    </body>
    </html>
    
    
    

    Output:

    
    PHP - Filter
    

What all are the different types of filter constants in PHP?

Below are some of the predefined filter constants:

Validate filter constants:

 1.    FILTER_VALIDATE_BOOLEAN: It is used to validate a Boolean data
 2.    FILTER_VALIDATE_INT: It is used to validate integer data
 3.    FILTER_VALIDATE_FLOAT: It is used to validate a float data
 4.    FILTER_VALIDATE_REGEXP: It is used to validate a regular expression
 5.    FILTER_VALIDATE_IP: It is used to validate an IP address
 6.    FILTER_VALIDATE_EMAIL: It is used to validate an e-mail address
 7.    FILTER_VALIDATE_URL: It is used to validate an URL

Sanitize filter constants:

 1.    FILTER_SANITIZE_EMAIL: It is used to remove all illegal characters from an e-mail address
 2.    FILTER_SANITIZE_ENCODED: It is used to remove/encodes special characters
 3.    FILTER_SANITIZE_MAGIC_QUOTES: It is used to apply addslashes() function
 4.    FILTER_SANITIZE_NUMBER_FLOAT: It is used to remove all characters, except digits, +- and optionally.
 5.    FILTER_SANITIZE_NUMBER_INT: It is used to remove all characters except digits and + –
 6.    FILTER_SANITIZE_SPECIAL_CHARS: It is used to remove special characters
 7.    FILTER_SANITIZE_FULL_SPECIAL_CHARS: It is used to encode quotes that can be disabled by using  FILTER_FLAG_NO_ENCODE_QUOTES.
 8.    FILTER_SANITIZE_STRING: It is used to remove tags/special characters from a string
 9.    FILTER_SANITIZE_STRIPPED: It is used as the alias of FILTER_SANITIZE_STRING
10.    FILTER_SANITIZE_URL: It is used to remove all illegal characters from the URL

Other filter constants:

 1.    FILTER_UNSAFE_RAW: It is used to do nothing, optionally strip/encode special characters
 2.    FILTER_CALLBACK: It is used to call a user-defined function to filter data