Thursday 23 August 2012

How to prevent sql injection in php

How to prevent sql injection in php !


SQL injection mean if any  user can send his own custom query to our database. SQL  injection is the most common problem when newbie or non-professional programmers develop websites.

For example : Here is a sql command
SQL injection Threat
$user=$_POST[‘username’];
$pass=$_POST[‘password’];

Select * from tablename where user=$user and Pass=$pass



If we execute this query, it will check if there is a record with username and password as provided by reader.
But what if a user enter password as 
Password= demo or 1=1;

Now the above sql query will become
Select * from tablename where user=$user and Pass=demo or 1=1;
 // this will let hacker enter into anyone’s account.

How to stop such attack ?

It’s very very simple, just use addslashes() function
$user=addslashes($_POST[‘username’]); // this will add slashes where  ever user introduces single quotes.
$pass=addslashes($_POST[‘password’]);


Now, above query is safe for any kind of sql injection. There is  a built in function in php with the name of magic_quotes_gpc() which handles such attack, if magic_quotes_gpc() is set to ON, all $_REQUEST, $_POST or $_GET values will be added slashed to it. However, in shared hosting, magic_quotes_gpc is mostly set to off for obvious reasons. In that case, you must validate input data with addslashes() function.

No comments:

Post a Comment