How to Filter data to prevent SQL Injection Attacks in PHP
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.
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.
Tutorial Categories:
why not use filter_var?
addslashes, strip_tags, trim, i think we need to use all of the available functions that helpful to unwanted material from strings then it will be good
You can also use PHP PDO class to make your database activities safe.
is encrypting techniques are useful in sql injection or any hacking
That’s such a great page !! Which is learn to us that how we protect the data by attacker through SQL injection, But this is not possible without any training form the best <a href="http://www.sagacademy.com/php-development-training-institute“>training institute or by the best place.
hello
how to use the function ?
thanks
you could just use pdo..
You can say via prepared statement we can make more secure, PDO is just mysql driver but approach should be same either we use mysqli, or pdo etc.
you could just use pdo..
Just use “$_POST[‘id’]” method. Even more secure.
thank your post