I have created a very simple function to filter 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.
$query = "select name from user where id=".$_GET['id']; // any one can inject in this query, by adding injection in url query sting.
$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:
// remove whitespaces from begining and end
$data = trim($data);
// apply stripslashes to pevent double escape if magic_quotes_gpc is enabled
$data = stripslashes($data);
// connection is required before using this function
$data = mysqli_real_escape_string($conn,$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 magicquotesgpcenabled 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.