Securing User Input in PHP

Posted on April 21, 2008

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.

function secure($string) {
		$string = strip_tags($string);
		$string = htmlspecialchars($string);
		$string = trim($string);
		$string = stripslashes($string);
		$string = mysql_real_escape_string($string);
	return $string;

	}

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: , ,

2 Responses

  1. Web Development Blog
    April 21, 2008

    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


  2. Panzer
    April 21, 2008

    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

You must be logged in to post a comment.