Organizational Research By

Surprising Reserch Topic

boostr.in questions - Question:how to use PHP Filter?


PHP filters are used to validate and filter data coming from insecure sources, like user input.


What is a PHP Filter?

A PHP filter is used to validate and filter data coming from insecure sources.

To test, validate and filter user input or custom data is an important part of any web application.

The PHP filter extension is designed to make data filtering easier and quicker.


Why use a Filter?

Almost all web applications depend on external input. Usually this comes from a user or another application (like a web service). By using filters you can be sure your application gets the correct input type.

You should always filter all external data!

Input filtering is one of the most important application security issues.

What is external data?

  • Input data from a form
  • Cookies
  • Web services data
  • Server variables
  • Database query results

Functions and Filters

To filter a variable, use one of the following filter functions:

  • filter_var() - Filters a single variable with a specified filter
  • filter_var_array() - Filter several variables with the same or different filters
  • filter_input - Get one input variable and filter it
  • filter_input_array - Get several input variables and filter them with the same or different filters

In the example below, we validate an integer using the filter_var() function:

$int = 123;

if(!filter_var($int, FILTER_VALIDATE_INT))
  {
  echo("Integer is not valid");
  }
else
  {
  echo("Integer is valid");
  }
?>

The code above uses the "FILTER_VALIDATE_INT"  filter to filter the variable. Since the integer is valid, the output of the code above will be: "Integer is valid".

Validating and Sanitizing

There are two kinds of filters:

Validating filters:

  • Are used to validate user input
  • Strict format rules (like URL or E-Mail validating)
  • Returns the expected type on success or FALSE on failure

Sanitizing filters:

  • Are used to allow or disallow specified characters in a string
  • No data format rules
  • Always return the string

Options and Flags

Options and flags are used to add additional filtering options to the specified filters.

Different filters have different options and flags.

In the example below, we validate an integer using the filter_var() and the "min_range" and "max_range" options:

$var=300;

$int_options = array(
"options"=>array
  (
  "min_range"=>0,
  "max_range"=>256
  )
);

if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
  {
  echo("Integer is not valid");
  }
else
  {
  echo("Integer is valid");
  }
?>

Like the code above, options must be put in an associative array with the name "options". If a flag is used it does not need to be in an array.

asked Sep 13, 2013 in PHP by rajesh
edited Sep 12, 2013
0 votes
13 views



Related Hot Questions



Government Jobs Opening


...