How to sanitize your php input?

Never trust user input, it may be malicious, always check your php input.
Check all global arrays like $_GET, $_POST, $_REQUEST, $_COOKIE, allow only known variables and make sure that they contain the right type of data.
What does this mean ? It means that if you have a $_GET['id'] variable in your script which has to be an integer, always check it and make sure it is an integer.
Also don't allow other variables in $_GET or other globals, keep only variables that your scripts need. So, if your script only uses only one variable $_GET['id'] then dispose other variables.
You can also use php filter to implement your sanitization code.

This is a simple function that sanitizes the data before sending it to MySQL. First it removes whitespaces from the beginning and ending of the string. If magic_quotes_gpc is enabled and the data has been already escaped we will apply stripslashes() to the data. This way the data won’t be escaped twice when mysql_real_escape_string() is called.

function sanitize($data)
{
// remove whitespaces (not a must though)
$data = trim($data);

// apply stripslashes if magic_quotes_gpc is enabled
if(get_magic_quotes_gpc())
{
$data = stripslashes($data);
}

// a mySQL connection is required before using this function
$data = mysql_real_escape_string($data);

return $data;
}

The function mysql_real_escape_string() escapes special characters in a string for use in a SQL Statement. Unlike the deprecated function mysql_escape_string(), which doesn’t take a connection argument and does not respect the current charset setting, mysql_real_escape_string() calls MySQL library’s function mysql_real_escape_string, which prepends backslashes() to the following characters: \x00, \n, \r, \, ‘, ” and \x1a. It’s strongly recommended to use this function before sending any query to the mySQL database.

[refer http://www.codeassembly.com/How-to-sanitize-your-php-input/]
0 Responses