
I was reading some articles about avoiding SQL injection. People used to use addslashes() function, and later more and more programmers are using mysql_real_escape_string(). What’s the difference between these two functions? Alan Storm from StackOverFlow gives a description which is the best as I know:
PHP’s mysql_real_escape_string function will, more or less, ask mysql what character(s) needs to be escaped, where the addslashses function will just add a backslash in front of and any single quote (‘), double quote (“), backslash (\) or NUL (the NULL byte) character.
In the same post, Waage says that:
mysql_real_escape_string adds slashes to:
\x00, \n, \r, \, ‘, ” and \x1a. characters.
Where addslashes only adds slashes to:
‘ \ and NUL
So that means mysql_real_escape_string() is better than addslashes(), I thought. If you still prefer addslashes(), you may like to have a look at this function from php5.idv.tw:
function quotes($content)
{
//if magic_quotes_gpc=Off
if (!get_magic_quotes_gpc())
{
//if $content is an array
if (is_array($content))
{
foreach ($content as $key=>$value)
{
$content[$key] = addslashes($value);
}
} else
{
//if $content is not an array
addslashes($content);
}
} else
{
//if magic_quotes_gpc=On do nothing
}
return $content;
}
This function checks if magic_quotes_gpc is on, if so, we don’t need to do addslashes(). if not, we do addslashes() in different way for array and non-array content.
Of course, you can write a similar function using mysql_real_escape_string(). Here is my version:
function quotes($content)
{
//if $content is an array
if (is_array($content))
{
foreach ($content as $key=>$value)
{
$content[$key] = mysql_real_escape_string($value);
}
} else
{
//if $content is not an array
mysql_real_escape_string($content);
}
return $content;
}
Basically, just replace addslashes() with mysql_real_escape_string(). You can use this function like this:
$name = quotes($_POST['user']); $password = quotes($_POST['password']);
Feel free to visit our Forum, subscribe our RRS Feed for news updates, and follow us on Twitter.
Pingback: Zack Live
Pingback: Zack Live