Home PHP Security: Sanitizing Strings, Validating Values, and Interrogating Integers

PHP Security: Sanitizing Strings, Validating Values, and Interrogating Integers

Trust no-one. Not just a tag-line for The X-Files, it’s also sound advice when dealing with data supplied by users.

Image

Whether a user is trying to do something nasty or they’ve just hit an unfortunate combination of keys, you shouldn’t assume that what you’re saving is trouble-free. Here are some tips for validating input in your PHP application.

Numbers Only

Zend Framework has a handy class called Zend_Filter_Int that will take a value and strip out any non-numeric characters. Or, you could do something like this:

$output = preg_replace("/[^0-9-.]/", "", $data);

This will allow negative numbers and decimal points.

Strip Tags, Display Tags

Don’t want any HTML? Use strip_tags. If you’d prefer to display HTML tags so a user can share a code snippet, use htmlspecialchars and the code won’t be parsed.

Escaping Strings in MySQL

Use mysql_real_escape_string to escape strings before sending them to MySQL. Or, use PDO and bind values to fields.

Use filter_input

Instead of using $_GET[‘id’], how about using filter_input instead?

$itemId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_SPECIAL_CHARS);

You can use INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV too.

What other methods do you use for sanitizing user input?

Photo by dheuer

About ReadWrite’s Editorial Process

The ReadWrite Editorial policy involves closely monitoring the gambling and blockchain industries for major developments, new product and brand launches, game releases and other newsworthy events. Editors assign relevant stories to in-house staff writers with expertise in each particular topic area. Before publication, articles go through a rigorous round of editing for accuracy, clarity, and to ensure adherence to ReadWrite's style guidelines.