PHP: Securing user input 06 Apr 2014

This is the first of a series of posts about writing PHP in a safe and secure manner. So to start things off I will be talking about the proper use of user input and how to safetly sanitize it.

First things first and most importantly USER INPUT IS NOT TO BE TRUSTED.

User input can come in different forms, data inputted into a form, HTTP requests (GET, POST, PUT, DELETE) and cookie information. To get started here is an example of an insecure way of handling user input.

$db->query("SELECT * FROM users WHERE id=" . $_GET['id']);

The above example is a shocking and improper use of user input that will cause a SQL Injection vulnerability. A better safer method would be to make sure the id value from $_GET is an integer you can do this like so.

$db->query("SELECT * FROM users WHERE id=" . (int) $_GET['id']);

The above example is better but still not very secure I would say. PHP has an in built function that can be used to filter user input (filter_var). Here is an example using filter_var function.

$id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
$db->query("SELECT * FROM users WHERE id=" . $id);

What I'm trying to say is all user input must be sanitized be it is used.

PHP has 4 global variables that are populated by user input:

  • $_GET
  • $_POST
  • $_FILES

There is also $_COOKIE this holds all the the HTTP Cookie info which can be changed or added to by the end user.

$_GET holds the values from a HTTP GET request. $_POST holds the values from HTTP POST request. $_FILES holds information about any files that have been uploaded. $_REQUEST holds the vales from $_GET, $_POST & $_COOKIE ($_REQUEST should never be used as you cannot verify where that data actually come from use $_GET, $_POST & $_COOKIE never $_REQUEST)

See the PHP documentation for $_REQUEST here & OWASP here. It is consider bad practice to use $_REQUEST.

Anyway here is a function that you can use to sanitize user input easily: Github Gist