Say I request this URL:
http://mydomain.com/script.php?var=2+2
$_GET['var'] will now be: "2 2" where it should be "2+2"
Obviously I could encode the data before sending and then decode it, but I'm wondering if this is the only solution. I could also replace spaces with plus symbols, but I want to allow spaces as well. I simply want whatever characters were passed, without any url decoding or encoding going on. Thank you!
Of course. You could read out $_SERVER["QUERY_STRING"]
, break it up yourself, and then forgo the usual URL decoding, or only convert %xx
placeholders back.
preg_match_all('/(\w+)=([^&]+)/', $_SERVER["QUERY_STRING"], $pairs);
$_GET = array_combine($pairs[1], $pairs[2]);
(Example only works for alphanumeric parameters, and doesn't do the mentioned %xx decoding. Just breaks up the raw input.)
if(strpos($_SERVER["QUERY_STRING"], "+") !== false){
$_SERVER["QUERY_STRING"] = str_replace("+", "%2B", $_SERVER["QUERY_STRING"]);
parse_str($_SERVER["QUERY_STRING"], $_GET);
}
You could use urlencode
, though that would also translate any spaces to a plus. This makes sense, because a +
in a URL usually represents a space. If you actually need a plus sign to mean a plus sign, you should probably escape the input. This means a +
would become %2B
and your URL would be http://mydomain.com/script.php?var=2%2B2
.
Whomever is generating the URL containing a +
in the query segment is wrong unless they intend it to represent a space character. A +
in the query is a reserved character (re: RFC2396 §3.4). If you need to insert a literal +
in the query string, then it must be encoded as %2B
(re: RFC2396 §2.2).
A few steps required to do it.
For future reference you can make the '+' symbol appear on a get request without the need submit the url with encoded symbols.
PHP Version 5.3.8
Submitting http://mydomain.com/script.php?var=2+2
Echo:
2+2
Using the following code:
<?php
echo urlencode($_GET['var']);
?>
I just used urlencode()
to - well - encode the URL and urldecode($_Get())
to make the string usable again.