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
- trim (filters spaces and new lines)
- htmlentities (cross site scripting security)
- htmlspecialchars (cross site scripting security)
- is_int (if is numeric)
- strlen (string length)
Conclusion, always use mysql_real_escape_string to prevent sql injection.
Nice post, computer security is essential.Discussing Web Security Threats to look out for
ReplyDeleteis_int () != is_numeric (). is_int() check integer, is_numeric () check strings and integers of numeric values.
ReplyDelete