This question already has an answer here:
Suppose a developer does not use prepared statements in mysql, so are the following three functions enough to prevent any SQL injection. I would be grateful if someone improves the following functions:
function SanitizeForSQL($str)
{
if( function_exists( "mysql_real_escape_string" ) )
{
$ret_str = mysql_real_escape_string( $str );
}
else
{
$ret_str = addslashes( $str );
}
return $ret_str;
}
/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = $this->StripSlashes($str);
if($remove_nl)
{
$injections = array('/(
+)/i',
'/(+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
Edit: Due to the response from the experts, it seems above code is a crap. So I will be using prepared statements. I thank all of you it was an eye opener.
</div>
The only way to improve your code is to scrap it altogether.
Besides being wrong in that you'll introduce charset-related bugs if you ever store multibyte strings and that your escaping function must be charset-aware, both the mysql
extension and gpc
quotes and deprecated and heading the way of the dodo. Don't use either.
Use pdo
instead, or mysqli
if you're married with mysql. In either case use parametrized queries -- also known as prepared statements.
And for that matter, you can also use an ORM that is well established and thoroughly battle-tested. There are many. This ORM will take care of the SQL for you, so you can worry about actually writing your app instead of your own framework.