MySql injection protection class in php

What is Mysql Injection?

SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database. Source – tizag.com.

Protection Class in PHP:

This is my own code to filtered unwanted inputs by user: [ Don't forget to comment here for improvement ]

<?php

class SQLProcess {

function filter($array) {

$keyarray = array();
$valuearray = array();
$outarray = array();

while (list($key, $value) = each($array)) {

if(get_magic_quotes_runtime()) {
set_magic_quotes_runtime(false);
}

$badWords = “(delete)|(update)|(union)|(insert)|(drop)|(http)|(–)|(script)|(iframe)|(alert)|(XSS)”;

//Values Filter
$filtervalues = eregi_replace($badWords,”‘”, $value);
$filtervalues = mysql_real_escape_string($filtervalues);
$filtervalues = htmlentities($filtervalues,ENT_QUOTES);

//Key Filter
$filterkeys = eregi_replace($badWords, “”, $key);
$filterkeys = mysql_real_escape_string($filterkeys);
$filterkeys = htmlentities($filterkeys,ENT_QUOTES);

array_push($keyarray,$filterkeys);
array_push($valuearray,$filtervalues);

}
$outarray = array_combine($keyarray, $valuearray);
return $outarray;
}

}

$Process = new SQLProcess;

?>

Example Usage:

$filter = $Process->filter($_REQUEST);

print_r($filter);

$_REQUEST is an array with total inputs given by users through form.

Note: Comment here to improve this class. And also mysql_real_escape_string() will works only when Database is used(connected). If you not using Database! replace mysql_real_escape_string with addslashes.

You can leave a response, or trackback from your own site.

4 Responses to “MySql injection protection class in php”

  1. N3msis says:

    Your class is powerfull but use a lot of CPU and cannot be used for large scale website (I think). You use regular expressions, mysql_real_escape_string and htmlentities. I have to say it, it would be hard to break this.
    What about just using (int)$_GET['val'] or (int)$_POST['val'] to secure INTEGER values transmitted ? Is it enough strong or can you break it and put malicious code ?

  2. @N3msis – I guess, this is the right track. I did’t take care on (int)$_GET['val'] or (int)$_POST['val']. If u interested to modify above class,u can do it. But don’t forget to share with all. Please.

  3. blue says:

    may i ask if where to put this codes??? index?? or function?? please…

  4. Vijaya Kumar says:

    Create new page in name sqlprocess.php

    and include the page at top of the page where u needed to filter the lines, as shown below,

    filter($_REQUEST);
    print_r($filter);
    ?>

    See the result..

Leave a Reply