PHP filter_input() function

Definition and Usage

The filter_input() function retrieves input from outside the script and filters it.

This function is used to validate variables from untrusted sources, such as user input.

This function can obtain input from various sources:

  • INPUT_GET
  • INPUT_POST
  • INPUT_COOKIE
  • INPUT_ENV
  • INPUT_SERVER
  • INPUT_SESSION (Not yet implemented)
  • INPUT_REQUEST (Not yet implemented)

If successful, it returns the filtered data, if failed, it returns false, if variable If parameters are not set, it returns NULL.

Syntax

filter_input(input_type, variable, filter, options)
Parameters Description
input_type Required. Specify the input type. Refer to the list above for possible types.
variable Specify the variable to be filtered.
filter

Optional. Specify the ID of the filter to be used. The default is FILTER_SANITIZE_STRING.

See the complete PHP Filter Functions reference manual for possible filters.

The filter ID can be an ID name (e.g., FILTER_VALIDATE_EMAIL) or an ID number (e.g., 274).

options Specify an array containing flags/options. Check each filter's possible flags and options.

Example

In this example, we use the filter_input() function to filter a POST variable. The accepted POST variable is a valid e-mail address.

<?php
if (!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL))
 {
 echo "E-Mail is not valid";
 }
else
 {
 echo "E-Mail is valid";
 }
?>

Output similar to:

E-Mail is valid