Should I url encode a query string parameter that's a URL?

Brad Parks picture Brad Parks · Sep 22, 2014 · Viewed 16.8k times · Source

Just say I have the following url that has a query string parameter that's an url:

http://www.someSite.com?next=http://www.anotherSite.com?test=1&test=2

Should I url encode the next parameter? If I do, who's responsible for decoding it - the web browser, or my web app?

The reason I ask is I see lots of big sites that do things like the following

http://www.someSite.com?next=http://www.anotherSite.com/another/url

In the above, they don't bother encoding the next parameter because I'm guessing, they know it doesn't have any query string parameters itself. Is this ok to do if my next url doesn't include any query string parameters as well?

Answer

CR Drost picture CR Drost · Sep 22, 2014

RFC 2396 sec. 2.2 says that you should URL-encode those symbols anywhere where they're not used for their explicit meanings; i.e. you should always form targetUrl + '?next=' + urlencode(nextURL).

The web browser does not 'decode' those parameters at all; the browser doesn't know anything about the parameters but just passes along the string. A query string of the form http://www.example.com/path/to/query?param1=value&param2=value2 is GET-requested by the browser as:

GET /path/to/query?param1=value&param2=value2 HTTP/1.1
Host: www.example.com
(other headers follow)

On the backend, you'll need to parse the results. I think PHP's $_REQUEST array will have already done this for you; in other languages you'll want to split over the first ? character, then split over the & characters, then split over the first = character, then urldecode both the name and the value.