SQL Injection

It seems that every day we are hearing new stories in the media of big sites being hacked. With this in mind I thought that I would offer some basic coverage of protection against SQL Injection.

SQL Injection is one of the most common methods used to gain access to a web application and take control. For example, it is done by hackers entering sql into dynamic parameters to gain access to the database and displaying all of the information from the database or to force a login to a system where the user credentials don’t exist.

To protect against this it is important that we check the data that is passed into the system from forms and url strings.

Using PHP Data Objects (PDO)

PDO is a PHP extension that work like class letting you access database more fast and secure.

$PSH=$db->prepare('SELECT * FROM table WHERE id = :id');
$PSH->execute(array(':id' => $_GET['id']));
$rows = $PSH ->fetchAll();

where $db is a success PDO connection

mysql_real_escape_string()

mysql_real_escape_string() is a function that escape the unsafe character before sending the MySQL query.

$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM table where id = "' .$id. '");

preg_replace()

preg_replace() is a function that find and replace character in string. Here we will use it to find anything but numbers and remove it.

This method is good if you are selecting from MySQL using WHERE id = INT;

$id = preg_replace("/[^0-9]/","", $_GET['id']);
$query = mysql_query("SELECT * FROM table where id = "' .$id. '");

Conclusion

Make sure that all data that is entered by a user is striped of anything that can be malicious. If you don’t you could end up loosing your application.

Always keep a backup of everything to!

Leave a Reply

Your email address will not be published. Required fields are marked *

*