Why does _GET in PHP wrongly decodes slash?

2019-07-13 09:08发布

问题:

Today I run into some oddity with PHP, which I fail find a proper explanation for in the documentation. Consider the following code:

<?php
echo $_GET['t']. PHP_EOL;
?>

The code is simple - it takes a single t parameter on the url and outputs it back. So if you call it with test.php?t=%5Ca (%5c is a '\'), I expected to see:

\a

However, this is what I got:

$ curl http://localhost/~boaz/test.php?t=%5Ca
\\a

Notice the double slash. Can anyone explains what's going on and give recipe for retrieving the strings as it was supplied on the URL?

Thanks, Boaz

PS. I'm using PHP 5.2.11

回答1:

This happens, because you have the "magic quotes" switch in php.ini switched on. From the manual:

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

Read more about it here: http://php.net/manual/en/security.magicquotes.php

To make your script aware of any value of the "magic_quotes_gpc" setting in php.ini, you can write your script like this:

$d = $_GET["d"];
if (get_magic_quotes_gpc()) $d = stripslashes($d);
echo $d; //but now you are kind of vulnerable to SQL injections
         //if you don't properly escape this value in SQL queries.


回答2:

You can easily fix this using the strip_slashes() function. You should avoid magic quotes; they've been deprecated for security reasons.



回答3:

open .htaccess file and put something like this

php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off 


标签: php get escaping