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?



1 Answer 1


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.

  • 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
    Commented Nov 16, 2010 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
    Commented Nov 16, 2010 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 &. Commented Nov 16, 2010 at 12:52
  • But if the url is got programmatically from a web page, and is not encoded? You should split the URL in parts and urlencode them separately? For example the URL mentioned in this question stackoverflow.com/questions/44841468/…, Or there is a smart function in PHP doing the job? Commented Jun 30, 2017 at 8:28
  • There is no smart function. You still need to know by yourself which parts are to be encoded and which don't, according to the RFC 3986 😕 (e.g. if you don't know a priori the parameter names then you should encode them too) [@see: stackoverflow.com/questions/51292397/… ] Commented Jul 11, 2018 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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