Function escaping quote is not working correctly

325 views Asked by At

I'm trying to figure out why this function does not work correctly.

It's adding an extra \ every time I edit my entries.

Online server has these settings:

magic_quotes_gpc On 
magic_quotes_runtime Off 
magic_quotes_sybase Off

Here is the code:

function esc($s)
{
  if (get_magic_quotes_gpc()) {
    if (ini_get('magic_quotes_sybase'))
      $s = str_replace("''", "'", $s);
    else
      $s = stripslashes($s);
  } //if 
  return mysql_real_escape_string($s);
}

Edit note:

I have tried completely removing this function to see what it does... and it does the same thing, so I have realized that addslashes is also use in the code for the same thing.

The extra \ were there because magic_quote was ON

3

There are 3 answers

0
lena On BEST ANSWER

Ok I have fixed the problem. A quick solution for now, I have removed function esc($s).
I changed Magic_Quote to OFF in php.ini.
I'm keeping addslashes solution.

2
tplaner On

You probably want to stripslashes even if magic_quotes_sybase is on:

function esc($s)
{
    if (get_magic_quotes_gpc()) {
        if (ini_get('magic_quotes_sybase'))
            $s = str_replace("''", "'", $s);
        
        $s = stripslashes($s);
    } //if 
    return mysql_real_escape_string($s);
}

You might also want to take a look at PHP's get_magic_quotes_gpc function page, there are several user comments on the page with fairly elegant solutions for ensuring slashes are stripped.

2
troelskn On

Your function makes little sense. If magic quotes is on (eg. input is escaped), you unescape it. If it's not on, you escape it. So you'll get different results, depending on if you have magic quote on or not.

In any case, relying on magic quotes is a really bad practice. You should:

  1. Disable magic quotes or reverse its effect globally.
  2. Either escape strings when you construct SQL queries or (better) use prepared statements.
  3. Not unescape/strip/whatever anything when you get it back from the database.