Home » , » How to strain data to ensure My SQL Injection Attacks here PHP

How to strain data to ensure My SQL Injection Attacks here PHP

Written By Unknown on June 06, 2014 | Friday, June 06, 2014

I have formed a very easy function to sort user input and form which you have to filter all your parameter before adding in MySQL to prevent SQL Injection. If some Hacker try to attack on your website database by SQL Injection then you have this solution to prevent those attacks, this function escape characters with slash like single quotation and double quotation like this \’ ‘\ & \” “\

Let see how attackers attack on your website using SQL Injection:

 http://www.website.com/user.php?id=1 user on this page and can see information from database  of id 1.

Your query:

$query = "select name from user where id=".$_GET['id'];
// any one can inject in this query, by adding injection in url query sting

Safe Query:

query = "select name from user where id=".some_escape_function($_GET['id']);
// Now its safe because it filter data in escape function.

Our Escape function:

function data_filter($data)
{
    // remove whitespaces from begining and end
    $data = trim($data);
   
    // apply stripslashes to pevent double escape if magic_quotes_gpc
        is enabled
    if(get_magic_quotes_gpc())
    {
        $data = stripslashes($data);
    }
    // connection is required before using this function
    $data = mysqli_real_escape_string($conn,$data);
    return $data;
}
First of all it removes whitespaces from the beginning and ending of the string using trim() function, then we check that magicquotesgpc is enabled then data has already escaped now apply stripslashes() to the data. If magicquotesgpc enabled then reason to use stripslashes() is to make sure that data won’t twice escaped when we apply mysqli_realescape_string() (need MySQL connection string before using this mysqli_escape function) on data.

This is a very simple and know method to all developers if you are developing PHP application you must use this function to make your website secure.

That’s all for today, I hope you liked this tutorial please feel free to comment your feedback and suggestion.

0 comments:

Post a Comment