June 2, 2014 8:07 am

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 \’ ‘\ & \” “\.

How to Filter data to prevent SQL Injection Attacks in PHP

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:

Safe Query:

Our Escape function:

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.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.

Tutorial Categories:
  • weldo

    why not use filter_var?

  • Tahir Khan Afridi

    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

  • Pritesh

    You can also use PHP PDO class to make your database activities safe.

  • is encrypting techniques are useful in sql injection or any hacking

  • Nitesh Khandelwal

    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.

  • lanner

    how to use the function ?

  • Μ.Ζ

    you could just use pdo..

    • salman

      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..

  • Innoxent Umar

    Just use “$_POST[‘id’]” method. Even more secure.

  • thank your post