Search code examples
phpmysqlsecuritysql-injection

MySQL/PHP - escaping characters that may slow my database down (or make it perform unexpectedly)


I run all my integers through a (int)Integer to make them safe to use in my query strings.

I also run my strings through this function code:-

if(!get_magic_quotes_gpc()) {
           $string = mysql_real_escape_string($string);
        }

$pattern = array("\\'", "\\\"", "\\\\", "\\0");
$replace = array("", "", "", "");
if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $string))) $string = addslashes($string); 


$cleanedString = str_replace('%','',$string);

I obviously return the $cleanedString variable. Now I replace the % character because it is a wildcard to mySQL and it could potentially slow down my queries (or make them return incorrect data) if the user inserted them. Are there any other special characters for mySQL I should be concerned about?

On a second note, is there anything wrong or redundant about my search and replace after the mysql_real_escape_string? I got it from a website when I was first starting out and (if I remember correctly) it said you had to use this search/replace in addition to the escape string. It looks like it's trying to remove any previously escaped injection characters?


Solution

  • yeah I think you've got things going a bit strangely there.

    First of all, I'd check for magic quotes and remove the slashes if it's turned on. That way you've got a string which actually represents the information you want (and not one that has been treated with slashes).

    If you particularly want to remove the % wildcard then you could just escape that or remove it altogether. Before you insert the string into an SQL query, finally run it through mysql_real_escape_string, and everything will be fine.

    $string = $_POST['searchTerm'];
    if (get_magic_quotes_gpc()) {
        $string = stripslashes($string);
    }
    $string = str_replace("%", "", $string);
    $safeString = mysql_real_escape_string($string);