Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

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

http%3A%2F%2Fwww.allposters.com%2Fgallery.asp%3Fstartat%3D%2Fgetthumb.asp%26txtSearch

which does not work when clicking on...

Trying to escape the QUERY only

startat%3D%2Fgetthumb.asp%26txtSearch

breaks the link also.

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

Thanks,

Joel

share|improve this question
add comment

1 Answer

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:

http://example.com/search.php?query=VALUE

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.

http://example.com/search.php?query=%2F.%20the%20book

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
add comment

Your Answer

 
discard

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.