PHP & MYSQL: Anti Sql Injection with mysql_real_escape_string function


<?php
$user="<div>spam spam</div>";
$password="<div>spam spam</div>";
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));
echo $query;
?>

Mysql command will be:

SELECT * FROM users WHERE user='
 ' AND password='
 '
<?php
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
$_POST['username'] = 'tutorialspots';
$_POST['password'] = "' OR ''='";
echo $query;
?>

Mysql command will be:

SELECT * FROM users WHERE user='tutorialspots' AND password='' OR ''=''

With this command will cause one user login without the correct password.
=> use mysql_real_escape_string to prevent the following:

<?php
$_POST['username'] = 'tutorialspots';
$_POST['password'] = "' OR ''='";
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", 
             mysql_real_escape_string($_POST['username']), 
             mysql_real_escape_string($_POST['password']));
echo $query;
mysql_query($query);
 ?>

Mysql command will be:

SELECT * FROM users WHERE user='aidan' AND password='\' OR \'\'=\''

Notice: you should use function getEscaped below instead of mysql_real_escape_string

function getEscaped( $text ) {
	/*
	* Use the appropriate escape string depending upon which version of php
	* you are running
	*/
	if (version_compare(phpversion(), '4.3.0', '<')) {
		$string = mysql_escape_string($text);
	} else 	{
		$string = mysql_real_escape_string($text);
	}
	
	return $string;
}

Leave a Reply