Webmasters Stack Exchange is a question and answer site for pro webmasters. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am using the PHP urlencode() function to escape chars for anchor tags (). Why can't I use the function on a full URL such as

http://www.allposters.com/gallery.asp?startat=/getthumb.asp&txtSearch= ...

The function converts this string to


which does not work when clicking on...

Trying to escape the QUERY only


breaks the link also.

So my question is which characters should I esacape using the urlencode() function?



share|improve this question
up vote 6 down vote accepted

URLEncode is meant to encode characters that have special meanings in URLs (like colons, question marks, slashes etc.).

You should only apply URLEncode to the values you wish to encode in your URL, not to the entire URL.

E.g. Suppose I have the following URL:


As it stands, no escaping is necessary. But suppose VALUE was actually

/. the book

The VALUE bit now contains a character that is not safe as a slash has special meaning in an URL.

So before I attach the VALUE to the URL, I need to URLEncode just the VALUE.


When a webserver gets the above request it will need to URLDecode the query parameter to make get the original text back.

In the example cited in the question, the entire query string was being encoded. This is incorrect as special characters (such as ampersands between query parameters) are then escaped and not interpreted correctly. You should only encode the parameter values.

share|improve this answer
So as a rule of thumb I should only escape params values (even if they do not contain special chars , is it still ok?) – Joel Nov 16 '10 at 10:52
@Joel Yes, if it contains no special characters then nothing will happen and if it does contain special characters it is absolutely necessary. – Kris Nov 16 '10 at 10:54
As I understand it, the non-param-values need to be entity-encoded when being put in an anchor. So, in this case, the ampersand that is being used to concatenate the query string parameters would need to be entity-encoded as &. – Lèse majesté Nov 16 '10 at 12:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.