Is it possible to preserve plus signs in PHP $_GET vars without encoding?

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!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

if(strpos($_SERVER["QUERY_STRING"], "+") !== false){
    $_SERVER["QUERY_STRING"] = str_replace("+", "%2B", $_SERVER["QUERY_STRING"]);
    parse_str($_SERVER["QUERY_STRING"], $_GET);
}

Solution 2

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.)

Solution 3

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.

Solution 4

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).

Solution 5

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']);
?>

Solution 6

A few steps required to do it.

  • Just replace your query parameter plus (+) sign with ‘%2B’ in the url
    before requesting the url.

  • Now you will just retrieve the query parameter. It will
    automatically replace ‘%2B’ with plus sign.

Solution 7

I just used urlencode() to – well – encode the URL and urldecode($_Get()) to make the string usable again.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply