Long time a go I wrote this article on how to prevent code injection in PHP, but is kind of old and uses the deprecated method “eregi”.
I rewrited the function and now looks like this, the hacker defense for php:
function clean($var){//request string cleaner
if(get_magic_quotes_gpc()) $var=stripslashes($var); //clean
$var=mysql_real_escape_string($var); //clean
return strip_tags($var, '');//returning clean var
}
function hackerDefense(){//thanks to Allen Sanford
// begin hacker defense
foreach ($_POST as &$postvalue){ //checking posts
$postvalue = clean($postvalue);//cleaning the value
}
} // end hacker defense
OLD way don’t use it!!!
function hackerDefense(){
// begin hacker defense
$notAllowedExp = array(
'/<[^>]*script.*"?[^>]*>/','/<[^>]*style.*"?[^>]*>/',
'/<[^>]*object.*"?[^>]*>/','/<[^>]*iframe.*"?[^>]*>/',
'/<[^>]*applet.*"?[^>]*>/','/<[^>]*window.*"?[^>]*>/',
'/<[^>]*docuemnt.*"?[^>]*>/','/<[^>]*cookie.*"?[^>]*>/',
'/<[^>]*meta.*"?[^>]*>/','/<[^>]*alert.*"?[^>]*>/',
'/<[^>]*form.*"?[^>]*>/','/<[^>]*php.*"?[^>]*>/','/<[^>]*img.*"?[^>]*>/'
);//not allowed in the system
foreach ($_POST as $postvalue) { //checking posts
foreach ($notAllowedExp as $exp){ //checking there's no matches
if ( preg_match($exp, $postvalue) ) die ("Code not allowed");//die!!!
}
}
// end hacker defense
}