Friday, August 24, 2012

How to filter & escape data from Injection attacks in PHP!

Ask any security expert! He will say you should always filter POST and GET data by escaping them before insertion into the database. In that way your scripts can be safe from SQL injection attacks.
Many php programmers are so lazy and just directly insert the POST data without filtering it like


mysql_query("INSERT into `users` (`name`,`email`) VALUES ('$_POST[name]','$_POST[email]')");

which is truly a bad example of not checking input data. Detect and protect important data from fraudulent access by having data security software.

A very good way to clean user input is using mysql_real_escape_function() which is a good way to protect from SQL injection attacks. You can use the function like this.



<?$name = mysql_real_escape_string($_POST['name']); ?>
This way you have to filter each and every POST variable. Imagine you have a form having hundreds of POST variable and how do you filter such data??

I was after a few lines of code where the server would automatically escape/filter POST data before inserting into database. It turns out that mysql_add_slashes() does the job but it causes more problems than anything and it is not advisable to use this function and it has been discontinued since PHP 6.0
Below is the nice little function that would filter/clean all user input and offers protection from
1. MySQL Injection attacks by escaping data.
2. Protection from XSS attacks through script tags.










function filter($data) {
    $data = trim(htmlentities(strip_tags($data)));
    if (get_magic_quotes_gpc())
        $data = stripslashes($data);
    $data = mysql_real_escape_string($data);
    return $data;
}
and to finally filter all POST variables in the form submitted, you have to loop through the array

foreach($_POST as $key => $value) {
    $mydata[$key] = filter($value);
}

and then finally you can use in the filtered array in your mysql statements.










mysql_query("INSERT into `users` (`name`,`email`) VALUES 
('$mydata[name]','$mydata[email]')");

all POST or GET variables in one go! Run the above code and see how this filters the user input data submitted from a form.

1 comment: