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

假装没事ソ 提交于 2019-11-26 22:04:47

问题


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!


回答1:


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




回答2:


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



回答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.




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




回答5:


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:


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



回答7:


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



来源:https://stackoverflow.com/questions/11979290/is-it-possible-to-preserve-plus-signs-in-php-get-vars-without-encoding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!