Jump to content

mysql_real_escape_string() VS SQL Injection


robert_gsfame

Recommended Posts

Well error reporting should only be on, on a development server,

by hole, I mean mysql_real_escape_string should be used on the all strings before the going to MySQL, using it on only 1 of 2 strings won't protect you.

 

ie, this statement uses mysql_real_escape_string but won't protect you from an injection

mysql_query("UPDATE table set firstname='".mysql_real_escape_string($POST['f_name'])."', lastname='".$POST['f_name']."' ");

 

take a look at Dan's PHP security Tutorial

mysql_real_escape_string, like its' name indicates is only usable for escaping string data (data that is put into a query inside of single-quotes.) It does nothing to prevent sql injection for numeric data put into a query (data that is not in single-quotes and the solution to this does not involve putting single-quotes around numeric data as that causes mysql to go through an extra step of converting the string containing a numeric value back to a number which it does by converting to a float.) Numeric data must be validate as numeric or it must be cast as a numeric data type in order to prevent sql injection (you can inject sql in this case without using any quotes around it by encoding it as a HEX hex value or producing a string using CONCAT()/CHAR() functions.)

I use this function on any variable that is about to be check with, or added to the database.  I think it might help you as well.

 

function clean($str){
$str = @trim($str);
if(get_magic_quotes_gpc()){
	$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Example
$username = clean($_GET['username']);
$q = mysql_query("SELECT password FROM users WHERE username = '$username'");
$n = mysql_num_rows($q);
if($n > 0){
   echo "User found!";
}else{
   echo "Error";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.