I’m trying to create a form which allows the user to define own custom query key and while I was testing the validation function for the form, I’ve noticed that %20 in a url query key is converted to a underscore in the $_GET array.
$key = 'a b';
$key = rawurlencode($key);
$value = 'value';
print_r($_GET); // output: Array ( [a_b] => value )
echo '<p>key:' . $key . '</p>';
echo '<p>value:' . $value . '</p>';
echo '<p><a href="' . $_SERVER["REQUEST_URI"] . '?' . $key . '=' . $value . '">test</a></p>';
Are there other characters converted irregularly? I’m not sure “irregular” is the right word here since there might be a rule for this behavior but I didn’t expect this would happen.
PHP replaces certain characters with an underscore because they are illegal in variable names. Even though they are legal in array keys, earlier versions of PHP would put form variables directly in variables (i.e.
$a_b; see Register Globals), so this conversion was put in. This is done with space, dot, open square bracket, and control characters between 128 and 159.This is only done with the names themselves, not to, for example, any array key parameters (i.e.
http://example.com/foo.php?a[b.%20c]=1) since any character is legal in an array key. (Note that the array parameter feature itself means that open square bracket will not be replaced with_as implied by the above in certain situations – the example will give$_GET['a']['b. c'] == 1.)Source: http://ca.php.net/variables.external
Related question: Get PHP to stop replacing '.' characters in $_GET or $_POST arrays?