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.


December 1st, 2009 at 5:30 PM
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 ?
December 2nd, 2009 at 1:37 PM
@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.
March 7th, 2010 at 8:54 PM
may i ask if where to put this codes??? index?? or function?? please…
March 10th, 2010 at 4:50 PM
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,
< ?php
include "your-path/sqlprocess.php";
$filter = $Process->filter($_REQUEST);
print_r($filter);
?>
See the result..