Thursday 18 April 2013

Security from SQL Injection

| |

 

SQL Injection:-

It is a basically a trick to inject SQL command or query as a input mainly in the form of the POST or GET method in the web pages.
Let’s look at the usual query for user login in PHP,
$sql=”SELECT * FROM tbl_user WHERE username= ‘”.$_POST['username'].”‘ AND password= ‘”.$_POST['password'].”‘”;

$result=mysql_query($sql);
Let’s suppose that an intruder injected x’ OR ‘x’='x in the username field and x’ OR ‘x’='x in the password field.
Then the final query will become like this,
SELECT * FROM tbl_user WHERE username=’x’ OR ‘x’='x’ AND password=’x’ OR ‘x’='x’;
Prevention from Sql Injection Attack in PHP:
1) Always restrict the length of the fields of form such as don’t allow more than 20 characters in the fields like username and password with the “maxlength” property available in the html form.
2) Always validate for the proper input like weather the value is valid email or not, is numeric or not , valid date or not etc.
3) Finally, Always use mysql_real_escape_string() function before sending the variable to the SQL query
For example
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
if an intruder inject ‘ OR 1 in the user name and password field then the value of the $username and $password will become \’ OR 1 which is not going to harm us anymore.


Paste this coding in your database coding to prevent SQL injection.

// To protect MySQL injection (more detail about MySQL injection)

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

0 comments:

Post a Comment