How to encode URL parameters?

Apoorv Saxena picture Apoorv Saxena · Nov 15, 2011 · Viewed 128.9k times · Source

I am trying to pass parameters to a URL which looks like this:

http://www.foobar.com/foo?imageurl=

And I want to pass the parameters such as an image URL which is generated itself by another API, and the link for the image turns out as:

http://www.image.com/?username=unknown&password=unknown

However, when I try to use the URL:

http://www.foobar.com/foo?imageurl=http://www.image.com/?username=unknown&password=unknown

It doesn't work.

I have also tried using encodeURI() and encodeURIComponent() on the imageURL, and that too doesn't work.

Answer

Niels picture Niels · Nov 15, 2011

With PHP

echo urlencode("http://www.image.com/?username=unknown&password=unknown");

Result

http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown

With Javascript:

var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);

DEMO: http://jsfiddle.net/Lpv53/