Monday, October 21, 2013

Preventing PHP websites from SQL injections

SQL injections are another pain for developers. If you have created a users database then you might save the users: name and password. But what if any hackers breaks the security of your website and get in to your users account unethically. So this might make your users not to trust on you and soon many others will leave your website.
What is SQL injection:
SQL injection is a way of breaking the websites SQL query and customize it according to the hacker.
For example, if your website query for user to login is:
$u = "Ashwin";
$p = "TheCodePress";
mysql_query("SELECT * FROM users WHERE uname='$u' AND upass='$p' ");

But if i'm a hacker then i'll simply do something like this to break the security of your login system:
$u = "Ashwin' -- ";
$p = "Hacked";
mysql_query("SELECT * FROM users WHERE uname='$u' AND upass='$p' ");

So, what i have done ?
I have simply entered my correct username but after that i have added ' -- and this means comment in SQL.
So we have commented the rest of the portion of the query. That means we now don't need to enter password, we'll directly login into the website.

How to Solve this problem:
Well, the best way to do it without using any library or API is to use in built PHP functions. Such as mysql_real_escape_string(); and htmlentities();
If you are using mysql_real_escape_string function then all the vulnerable symbols will be parse, but it will parse safely.

PHP Code: So the code will be something like this:
$u = mysql_real_escape_string("Ashwin' -- ");
$p = mysql_real_escape_string("Hacked");
mysql_query("SELECT * FROM users WHERE uname='$u' AND upass='$p' ");

Is their any other better way to do it?
Yes, you can use the Library such as PDO or MYSQLI.
If you are more familiar with object oriented programming (OOP) then i'll prefer you to go with PDO.
Soon, i'll be too writing tutorials about PDO and Mysqli. You can learn it now on PHP manual.

Liked the post ? subscribe us with your email to get upcoming tutorials directly in your inbox:

1 comment:

Your Comment Will Be Visible After Approval, Thanks !