Is it possible to preserve plus signs in PHP $_GET

2019-01-15 19:04发布

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!

标签: php encoding get
7条回答
欢心
2楼-- · 2019-01-15 19:32

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']);
?>
查看更多
甜甜的少女心
3楼-- · 2019-01-15 19:38
if(strpos($_SERVER["QUERY_STRING"], "+") !== false){
    $_SERVER["QUERY_STRING"] = str_replace("+", "%2B", $_SERVER["QUERY_STRING"]);
    parse_str($_SERVER["QUERY_STRING"], $_GET);
}
查看更多
家丑人穷心不美
4楼-- · 2019-01-15 19:43

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.

查看更多
别忘想泡老子
5楼-- · 2019-01-15 19:43

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.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-15 19:43

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

查看更多
Evening l夕情丶
7楼-- · 2019-01-15 19:48

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

查看更多
登录 后发表回答