Question

I'm really confused here, can someone explain this to me?

request: http://example.com/test.php?var=String's

$a = $_GET["var"];
$b = "String's";

echo $a . "<br/>";
echo $b . "<br/>";

$output = mysql_real_escape_string($a);
$output = mysql_real_escape_string($b);
echo "<hr/>";
echo $a . "<br/>";
echo $b . "<br/>";

result:

String\'s
String's
----------------
String\'s
String's

Could someone explain to me not only why my GET variable is being transformed like this, but how I can remove this behavior such that my input is exactly as it was sent? I'm having an issue where my SQL wrapper passes this through mysql_real_escape_string() and ends up being String\\\'s :(

Was it helpful?

Solution

It's called "magic quotes".

OTHER TIPS

You can and should disable magic quotes.


prefered mode
set them off in php.ini


.htaccess mode
add this to your htaccess file

php_flag magic_quotes_gpc off


php5 runtime mode

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_gpc(&$value)
    {
        $value = stripslashes($value);
    }
    array_walk_recursive($_GET, 'stripslashes_gpc');
    array_walk_recursive($_POST, 'stripslashes_gpc');
    array_walk_recursive($_COOKIE, 'stripslashes_gpc');
    array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}
?>


php4 runtime mode

<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>


Welcome to the magic_quotes hater's club! :)

You probably have magic quotes turned on. This automatically escapes GET, POST and COOKIE data. Magic quotes is bad and should not be relied upon to properly escape data.

If you have access to php.ini, you can turn magic quotes off.

If you don't, you can run stripslashes on the data to remove the slashes. In order to make your code portable, you should first check get_magic_quotes_gpc() to see if it is turned on and only then run stripslashes. In this way, if you move your code to a server that has magic quotes turned off, your code will still work.

if(get_magic_quotes_gpc()) {
    $a = stripslashes($_GET["var"]);
}
else $a = $_GET["var"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top