Form Validation in PHP

When you are dealing with form data, you have some of the most dangerous data around within your application.

So many of the recent exploits have relied upon poor validation of form data, that you really cannot afford not to carefully check data before accepting it.

MySQL

Inserting data into a mysql database opens you to the well known MySQL injection attacks. The easiest way to resolve this is to escape the values before inserting them as follows:

mysql_escape_string($value)

Globals, etc

With register_globals on, if I set ?userid=1 in the URL, or by manipulating a form, then the variable $admin becomes equal to 1 within the code. This is a very common form of insecurity.

There are two ways to fix this - first - check the value of key variables against an internal session or those stored in a database, but more easily, just turn register_globals to off, which is now recommended by the PHP group.

Now, when you want to access form variables use:

$_POST['admin']
or
$_GET['admin']

Likewise, sessions are accessed as:

$_SESSION['admin']

Integers are integers

Use functions such as intval() and preg_replace to only allow through the values which can legitimately be permitted. If you don't want to allow all kinds of dodgy accented characters and double byte characters in your application, then a simple:

$text=preg_replace("/[^a-z0-9\ \.\,\!\?/ism","",$text);

Will strip them out for you. By explicitly saying what you DO want in, you are certain not to forget some characters.

HTML tags messing up my text

There are two ways to treat this. Either strip out everything which starts with < and ends with > (remembering tricks relating to > and <, and that these may break across lines), or use htmlentities() which will return them in a form where they are displayed as 'source'.

If you do want some tags, but not others, I would suggest you recognise the tags you want, and mark them as safe first, i.e. to allow bold:

$text=preg_replace("/\<b\>(.*?)\<\/b\>/","[b]$1[/b]",$text);

Then, strip out all the HTML tags as normal - you've now got BBCode style [b] tags, which you can convert back to <b> </b> html either before storing the form data, or upon output.
Search for Freelance jobs

Keyword:

Advanced Search





 


Copyright 2004 SofterLogic Ltd. All rights reserved. Hair Transplant Information Disneyland Hong Kong Second Hand Cars Office Stationary