Author: Hjalle - 2008-03-28

Preventing SQL injections

10/10

SQL injections are common nowadays and plenty of sites get hacked because of insecure database calls.

Making it bulletproof against injections is hard and will take time, but making safer calls are essential and doesn’t take that long to make.


So, what is a SQL injection?

To clearify it I will give a very easy example:


A database may look something like this:

ID | USERNAME | PASSWORD


When you make a call to that database your query can look something like this:


SELECT * FROM database_name WHERE id = '2'


So far no problems.. But when you code it, it will be something like this (the insecure way):


$sql = "SELECT * FROM database_name WHERE id = '".$_POST['id']."'";


If you make that query and has a id that is “2″, there will be no problem, but if you change it to something else, you will get some problems.


What if $_POST[’id’] would contain something like: ‘ or 1=1– ?


The query would now be:


$sql = "SELECT * FROM database_name WHERE id = '' or 1=1--";


That would automaticly select the whole database since that “or 1=1″ definetly is true.


That was a very short description of what a SQL injection is so how can we now prevent without using any PDO? Using PDO may be the most secure way but requires more knowledge too.


Three lines of code will secure your code against the most known injections and will make it a lot harder to inject your site and hack it. One of this lines will take care of XSS hacking methods too:


$_POST = array_map("htmlspecialchars", $_POST); # Will secure from XSS

$_POST = array_map("trim", $_POST); # Remove spaces before and after posts

$_POST = array_map("mysql_real_escape_string", $_POST); # Protects from most known SQL injections


Just add these lines in the top include file and you will always have your $_POST protected from the most known SQL injections. One easy way of securing your web applications a little further.


Rate:
Add Comment

Title:

Comment:

Author:

Comments ( 0 )