Take the 2-minute tour ×

I am new to the world of coding and PHP hence would like to learn what's the best way to sanitize form data to avoid malformed pages, code injections and the like. Is the sample script I found below a good example?


share|improve this question
It does look useful. Albeit the htmlentities should be replaced with htmlspecialchars and declare the charset parameter. –  mario May 2 '11 at 23:26
add comment

4 Answers

up vote 4 down vote accepted

Your example script isn't great - the so called sanitisation of a string just trims whitespace off each end. Relying on that would get you in a lot of trouble fast.

There isn't a one size fits all solution. You need to apply the right sanitisation for your application, which will completely depend on what input you need and where it's being used. And you should sanitise at multiple levels in any case - most likely when you receive data, when you store it and possibly when you render it.

Worth reading, possible dupes:

What's the best method for sanitizing user input with PHP?

Clean & Safe string in PHP

share|improve this answer
Thanks. How do you test for all possible scenarios or at least a subset if these? –  PeanutsMonkey May 3 '11 at 0:43
@PeanutsMonkey - The approach used in your example was fine - i.e. call a universal sanitisation function which only admits in data you specifically define, with a type you specifically requested. That part is good. The problem was the sanitisation needs to be robust enough. Sanitising numbers is easy (something like $i = (float) $i;), the problem is usually with strings, as these are vulnerable to both SQL injections and XSS attacks. You really need to know what your strings are being used for to do this though. E.g. must they support foreign characters? –  Oliver Emberton May 3 '11 at 10:42
add comment

That script has some nice functions but it doesn't do a good job at sanitizing!

Depending on what you need (and want to accept) you can use:

  • abs() for positive numbers (note that it accepts floats also)

  • preg_replace('/[^a-zA-Z0-9 .-]/','',$var) for cleaning out any special characters from strings or preg_replace('/\D/','',$var) to remove all non-digit characters

  • ctype_* functions eg. ctype_digit($var)

  • filter_var() and filter_input() functions

  • type-cast eg. (int)$_GET['id']

  • convert eg. $id=$_GET['id']+0;

share|improve this answer
Thank. Is it better to use regular expressions to remove special characters? Why not use htmlspecialchars? –  PeanutsMonkey May 2 '11 at 23:46
add comment

As a general rule if you are using PHP & MySQL you will want to sanitize data going into MySQL like so:

$something = mysql_real_escape_string($_POST['your_form_data']);


share|improve this answer
add comment

It's not bad.

For SQL, it'd be best to avoid the need to risk the scenario at all, by using PDO to insert parameters into your queries.

share|improve this answer
add comment

Your Answer


