Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should space be encoded to plus (+) or %20? [duplicate]

Tags:

urlencode

Sometimes the spaces get URL encoded to the + sign, and some other times to %20. What is the difference and why should this happen?

like image 896
Muhammad Hewedy Avatar asked Apr 20 '10 20:04

Muhammad Hewedy


People also ask

Why is %20 space replaced?

This ensures that characters that would otherwise have special meaning don't interfere. In your case %20 is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".

How do you handle space in query string?

Our recommendation is to avoid using spaces in URLs, and instead use hyphens to separate words. If you are unable to do this, make sure to encode whitespace using "+" or "%20" in the query-string, and using "%20" within the rest of the URL.

How do you handle spaces in a URL?

An URL can use spaces. Nothing defines that a space is replaced with a + sign. As you noted, an URL can NOT use spaces. The HTTP request would get screwed over.


1 Answers

+ means a space only in application/x-www-form-urlencoded content, such as the query part of a URL:

http://www.example.com/path/foo+bar/path?query+name=query+value 

In this URL, the parameter name is query name with a space and the value is query value with a space, but the folder name in the path is literally foo+bar, not foo bar.

%20 is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20 and pluses with %2B. This is what, e.g., encodeURIComponent() does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).

See Also

HTML 4.01 Specification application/x-www-form-urlencoded

like image 180
bobince Avatar answered Oct 18 '22 10:10

bobince