Securing User Input in PHP

In nearly all of my PHP tutorials you’ll see me using the secure function to sanitise incoming user data from things like forms, and $_GETs . Its a small function, which no doubt alot of you already have, but here it is anyway.

  1. function secure($string) {
  2.                 $string = strip_tags($string);
  3.                 $string = htmlspecialchars($string);
  4.                 $string = trim($string);
  5.                 $string = stripslashes($string);
  6.                 $string = mysql_real_escape_string($string);
  7.         return $string;
  8.  
  9.         }

As you can see, it basically sanitises the heck out of everything. Some people say its an overkill but you can use it in almost every situation when user data is incoming.

Tags: , ,

This entry was posted on Monday, April 21st, 2008 at 2:57 pm and is filed under php, security, snippet. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Securing User Input in PHP”

Web Development Blog April 21st, 2008 at 3:09 pm

Its an alright function, but you can’t alway use mysql_real_escape_string, when it comes down to input security. Some sites might not use sql. Also, you might need to check if magic quotes is on before stripping slashes :).

Heres something I’ve writing in the past.

function input_sanatize($data,$trim=true,$type=1)
{
if( is_array($data) )
{
for($x=0;$x<sizeof($data);$x++)
{
$data[$x] = input_sanatize($data[$x],$trim,$type);
}
return $data;
}
else
{
$data = get_magic_quotes_gpc() ? stripslashes($data) : $data;
$data = $trim === true ? trim($data) : $data;
switch( $type )
{
case 1:
$data = mysql_real_escape_string($data);
break;
case 2:
default:
$data = htmlentities($data, ENT_QUOTES,’UTF-8′);
break;
}
}
return $data;
}

Regards,
-Lamonte

Panzer April 21st, 2008 at 3:30 pm

Thats a good point, about not being able to use mysql_real_escape if you don’t use MySQL in the first place.

Leave a Reply