简体   繁体   中英

How to pass special characters in a URL

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

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

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

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.

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM