Muntashir Akon
Muntashir Akon

Reputation: 9441

PHP - When to filter user input

Consider this code:

// store the $name into a database
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);

// already encrypted password (client-side) and will be salted or hashed again to store it into DB
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

// just to check if the $lang is on the $language array i.e. in_array($lang, $language)
$lang = filter_input(INPUT_POST, 'language', FILTER_SANITIZE_STRING);

// just to echo something
$sth = filter_input(INPUT_POST, 'sth', FILTER_SANITIZE_STRING);

Here I tried to describe some situations. And in each situation, I filtered user input (in some cases it was not necessary). My question is when to filter user input as it seems filtering user input is not always necessary.

Upvotes: 0

Views: 422

Answers (1)

Emotional_Goose
Emotional_Goose

Reputation: 167

this might gives you a better understanding of input validation:

Input validation is both the most fundamental defense that a web application relies upon and the most unreliable. A significant majority of web application vulnerabilities arise from a validation failure, so getting this part of our defenses right is essential. Even where we do appear to have gotten it down, we’ll need to be concious of the following considerations.

You should bear these in mind whenever implementing custom validators or adopting a 3rd party validation library. When it comes to 3rd party validators, also consider that these tend to be general in nature and most likely omit key specific validation routines your web application will require. As with any security oriented library, be sure to personally review your preferred library for flaws and limitations. It’s also worth bearing in mind that PHP is not above some bizarre arguably unsafe behaviours. Consider the following example from PHP’s filter functions:


filter_var('php://', FILTER_VALIDATE_URL);

The above example passes the filter without issue. The problem with accepting a php:// URL is that it can be passed to PHP functions which expect to retrieve a remote HTTP URL and not to return data from executing PHP (via the PHP wrapper). The flaw in the above is that the filter options have no method of limiting the URI scheme allowed and users’ expect this to be one of http, https or mailto rather than some generic PHP specific URI. This is the sort of generic validation approach we should seek to avoid at all costs.

further details available at : http://phpsecurity.readthedocs.org/en/latest/Input-Validation.html

Upvotes: 1

Related Questions