Monday, 6 August 2018

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
1mysql_query("INSERT into `users` (`name`,`email`)
2VALUES ('$_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.
1<?
2$name = mysql_real_escape_string($_POST['name']);
3?>
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.
01function filter($data) {
02  $data = trim(htmlentities(strip_tags($data)));
03 
04  if (get_magic_quotes_gpc())
05    $data = stripslashes($data);
06 
07  $data = mysql_real_escape_string($data);
08 
09  return $data;
10}
and to finally filter all POST variables in the form submitted, you have to loop through the array
1foreach($_POST as $key => $value) {
2  $mydata[$key] = filter($value);
3}
and then finally you can use in the filtered array in your mysql statements.
1mysql_query("INSERT into `users` (`name`,`email`)
2VALUES ('$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.

0 comments:

Post a Comment