Friday, October 7, 2011

Protection from sql injection in PHP

There are many points which are needed to stop sql injection in PHP. One of them is discussed below.
We will focus on escaping the characters which allow sql injection. Let say we have a table:

Required: MySQL, PHP

Using:
table1:
         id (int)
         name (char)

Now if we use a query,

"SELECT id FROM table1 WHERE name = ".$name;

Here $name is a php vairable. Now lets try to hack this query. I will use one example here for that.
If we pass a value ALL (SELECT name FROM table1) into $name and it will reply to us with all the ids in table1. So in order to prevent such disaster we are going to use some methods of PHP itself.

First, is the mysql_real_escape_string() and the second one is addslashes().
While running query use the above functions like  addslashes(mysql_real_escape_string($name)).

Explanation:

mysql_real_escape_string() - what it does is escape the special characters in string. like hexadecimal.
addslashes() - this introduces slashed before the quotes.

Note:

  1. First use mysql_real_escape_string() then addslashes over it if you are entering value in database.
  2. To invert the procedure which will be needed when fetching values use stripslashes() twice over the value and it will give you the original value.

No comments:

Post a Comment

Thank you for your comment!