André
André

Reputation: 307

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

Upvotes: 2

Views: 10143

Answers (5)

LOKENDRA
LOKENDRA

Reputation: 391

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

Upvotes: 0

André
André

Reputation: 307

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.

Upvotes: 5

MonkeyZeus
MonkeyZeus

Reputation: 20747

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"

Upvotes: 1

user1646111
user1646111

Reputation:

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

Upvotes: 1

lsouza
lsouza

Reputation: 2488

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

Upvotes: 2

Related Questions