View Single Post
Old 12-05-2007, 11:04 AM   #1 (permalink)
Rendair
The Addict
Upcoming Programmer Top Contributor 
 
Rendair's Avatar
 
Join Date: Nov 2007
Location: UK
Posts: 319
Thanks: 18
Rendair is on a distinguished road
Default SQL injections protection

Hey all

I thought i would write a tutorial on SQL injections and just how easily they can effect programmers who don't project their code. This is mainly for people who are new to programming and taking into account the security of the databases you use i find is very important.

What is it?

SQL injections are ways for a hacker to break your code and be able to crack into your databases and get more information then you wanted people to.

How do they do it?


If say you have a user login system and a hacker comes along. He can type the following into the username box or the password box:

PHP Code:

// user input that uses SQL Injection
$name_bad $_POST["username"]; // they enter 'OR 1=1

//inturn the SQL query below will look like the following
 
$query_bad "SELECT * FROM members WHERE username = ''OR 1=1"
The query above will always return true, by using a single quote (') they have ended the string part of our MySQL query.So every single entry in the "members" table would be selected by this statement!

This can cause some big problems if your web host hasn't protected their MySQL on their side to stop this, some of them do. If you find they haven't the good ppl of PHP knew about this problem and proved a nice function called mysql_real_escape_string();


we use that function to prevent the MySQL injection.

[php]
$username = mysql_real_escape_string($_POST["username"]);


What is it?

SQL injections are ways for a hacker to break your code and be able to crack into your databases and get more information then you wanted people to.

How do they do it?


If say you have a user login system and a hacker comes along. He can type the following into the username box or the password box:

PHP Code:


$username 
mysql_real_escape_string($_POST["username"]);
$query_bad "SELECT * FROM members WHERE username = '$username'"
Now that query will look like the following

PHP Code:
SELECT FROM members WHERE username '\' OR 1\'' 
The function uses backslashes to escape them evil injects.

Stopping them before they reach MySQl Query

Now i found a way of stopping them from even reaching the MySQL query. You can check if the user has entered a ' and then display an error.

PHP Code:
$username $_POST["username"];
$check explode("'",$username);
  if(
$check[1])
  {
     echo 
"You are trying to use MySQL injects!"
  
}else{
    
//double check incase
    
$username mysql_real_escape_string($_POST["username"]);
    
    
//query here
  

__________________
www.jooney.co.uk - the online portfolio
Send a message via MSN to Rendair
Rendair is offline  
Reply With Quote
The Following 2 Users Say Thank You to Rendair For This Useful Post:
codefreek (12-29-2007), Karl (12-05-2007)