Thursday, March 13, 2008

Input Validation for Security in PHP

In an effort of fair play, I will extend my post regarding input validation in Classic ASP and now post the same concepts and how to apply it to PHP.

For many of the same reasons, PHP is best served by cleansing user-supplied input upon receiving it. Like Classic ASP, doesn't really have explicit data types upon variables, for this reason, it's nice to have a function to ship input through to make sure it is what you expect it to be, and to sanitize it for inclusion into a database, email message or web display.

Via querystrings or submitted form data a user can inject malicious code used to hack your database, XSS script or obtain high level permissions on the server or the directory structure.

The function I rely on for PHP is much simpler than my ASP functions due to the fact PHP has some built in functions that are pretty handy, and this function certainly can be expanded on to encompass the additional datatypes that my ASP functions do.

Function clean_input($value, $type, $length)
{
if(empty($value))
$rtn_value = "";
else if($type == "int" && is_numeric($value) && strlen($value) <= $length)
$rtn_value = $value;
else if($type == "str" && strlen($value) <= $length)
$rtn_value = mysql_real_escape_string($value);
else
die("Can not process this request, invalid input data.");
return $rtn_value;
}

This function supports fewer datatypes, though it could, I just haven't had the need as yet to expand this function as I have had to for a couple of ASP projects. The very same regular expression concepts can be used in PHP with the eregi() function, as well as other regex functions PHP has.

Thanks to the mysql_real_escape_string() PHP function, it is incredibly easy to properly escape possibly malicious code before inserting the data into the database.

0 comments: