Aug 1, 2012

Sql Injection security tutorial | Web Security part 1

sql injection

In this tutorial about preventing sql injection we will explain various methods to keep a blog safe against attackers.

We will focus on three php functions:
1. mysql_real_escape_string() 2.
int/is_numeric etc..
3. string length (tip)
Lets start with mysql_real_escape_string.
It's a php function made for the prupose of escaping dangerous charachters.

Before starting i suggest you read Php Mysql post to database and Building a blog with Php and Mysql


Now lets explain what mysql_real_escape_string does

1. Filters dangerous charachters against sql injection.
2. Keep us safe

Note! this function does not work when a nysql connection is not set, for filtering stuff when no mysql database is added we can use htmlspecialchars() or htmlentities()

Im gonna show a simple script which is vulerable to sql injection, i suppose you know to build one.
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
mysql_query("UPDATE users SET pass=$pass WHERE user=$user");
?>


That script suffers from Sql Injection and is not safe for use but we can make it to.

<?php
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
mysql_query("UPDATE users SET pass=$pass WHERE user=$user");
?>



We can also use htmlspecialchars or htmlentities with mysql_real_escape_string


Other things to try

  1. trim (filters spaces and new lines)
  2. htmlentities (cross site scripting security)
  3. htmlspecialchars (cross site scripting security)
  4. is_int (if is numeric)
  5. strlen (string length)
And finally

  1. php chaptcha (anti spam)
  2. protecting folder using php
  3. limiting string length tutorial



Conclusion, always use mysql_real_escape_string to prevent sql injection.

2 comments:

  1. Nice post, computer security is essential.Discussing Web Security Threats to look out for

    ReplyDelete
  2. is_int () != is_numeric (). is_int() check integer, is_numeric () check strings and integers of numeric values.

    ReplyDelete