How to Use the PHP filter_input() Function

09/05/2021

Contents

In this article, you will learn how to use the PHP filter_input() function.

PHP filter_input() Function

The PHP filter_input() function is used to get a specific input from external sources, such as GET, POST, COOKIE, etc. and sanitize it based on a specified filter.

Syntax:
filter_input(type, variable_name, filter, options)
Parameters:
  • type: Specifies the type of the input, either INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
  • variable_name: Specifies the name of the variable to retrieve.
  • filter: Specifies the ID of the filter to apply, using one of the built-in PHP filter constants.
  • options: Specifies any additional options to pass to the filter, as an array or a flag.
Example:
<?php
  $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
?>

In this example, the function is retrieving the ’email’ variable from the $_POST array, sanitizing it with the FILTER_SANITIZE_EMAIL filter, and storing it in the $email variable.

The filter_input() function is useful for validating and sanitizing user input received from external sources, such as form submissions or query parameters. This helps prevent security vulnerabilities, such as cross-site scripting (XSS) or SQL injection attacks.

Some commonly used filters in filter_input() are:

  • FILTER_VALIDATE_INT: Validates the input as an integer.
  • FILTER_VALIDATE_FLOAT: Validates the input as a floating-point number.
  • FILTER_VALIDATE_BOOLEAN: Validates the input as a boolean value.
  • FILTER_VALIDATE_EMAIL: Validates the input as an email address.
  • FILTER_SANITIZE_STRING: Removes any tags or special characters from the input.
  • FILTER_SANITIZE_ENCODED: URL-encodes the input.
  • FILTER_SANITIZE_SPECIAL_CHARS: Converts special characters to HTML entities.

Note: The filter_input() function returns the filtered value on success, or FALSE on failure. It’s important to check the return value for validity before using it.