How to pass special characters in a URL

2019-08-06 02:34发布

问题:

I am trying to send a classic GET request to an API : http://mywebsite.com?arg1=val1&arg2=val2. The problem is I don't know what to do if val1 or val2 contains a "&" or "?" character. I know the urlencode() function but I'm not sure it would help in this case as there needs to be a difference between the "&" used to separate the arguments and the "&" contained by the arguments.

Can anyone help? Thanks

回答1:

Perhaps you could try to use http_build_query().

http://php.net/http_build_query

$data = array('foo'=>'bar',
              'baz'=>'a&c',
              'cow'=>'d?f');

echo http_build_query($data); // foo=bar&baz=a%26c&cow=d%3Ff


回答2:

if you pass these variables manually, you should urlencode(), if not, browser will do this for you automatically.

Also, for PHP side, no need to urldecode() because PHP will do it for $_GET, $_COOKIE, $_POST



回答3:

I finally found a much simpler solution. urlencode() did the trick:

$url = 'http://mywebsite.com?arg1='.urlencode('val1').'arg2='.urlencode('val2').......

Thank you all for your replies.



回答4:

I would personally do this:

$your_array = array('1'=>'something', '2'=>'another thing!');
$send_in_url = json_encode($your_array);
$send_in_url = base64_encode($send_in_url);

header('Location: www.mywebsite.com?code='.$send_in_url);

In your API you will do:

$code = base64_decode($_GET['code']);
$array = json_decode($code);

echo $array[1]; // this will output "something"


回答5:

it worked well, I was using simple encode/decode which in general ignores ! or any other special symbol. base64_encode does this.