How to pass special characters in a URL

2019-08-06 02:00发布

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

5条回答
Evening l夕情丶
2楼-- · 2019-08-06 02:28

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

查看更多
混吃等死
3楼-- · 2019-08-06 02:34

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楼-- · 2019-08-06 02:40

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

查看更多
萌系小妹纸
5楼-- · 2019-08-06 02:47

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"
查看更多
够拽才男人
6楼-- · 2019-08-06 02:55

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
查看更多
登录 后发表回答