PHP urlencode vs rawurlencode Difference
This article explains the differences between PHP’s
urlencode() and rawurlencode() functions,
detailing how each handles character encoding for URLs. You will learn
the historical standards behind them, how they treat spaces and special
characters, and when to use each function in your web development
projects.
While both urlencode() and rawurlencode()
are used to encode strings for use in URLs, they adhere to different
encoding standards, which leads to different outputs—most notably when
handling spaces.
The Core Difference: How Spaces are Encoded
The primary difference between the two functions lies in how they encode the space character:
urlencode()encodes a space as a plus sign (+).rawurlencode()encodes a space as%20.
Technical Standards
The difference in behavior stems from the historical Internet standards they implement:
urlencode()implements theapplication/x-www-form-urlencodedmedia type. This format is historically used for encoding query strings in HTML forms. Under this standard, spaces are replaced with plus signs.rawurlencode()implements RFC 3986 (Uniform Resource Identifier Generic Syntax). This is the modern, standard way to encode URLs so they are compatible across all web browsers and servers. Under RFC 3986, spaces must be percent-encoded as%20.
Character Comparison
Beyond spaces, there are minor differences in how older versions of
PHP handled other characters like the tilde (~).
rawurlencode()leaves the tilde (~) unencoded as per RFC 3986.- In older PHP versions (prior to PHP 5.3),
urlencode()encoded the tilde as%7E, though modern PHP versions have standardized this.
Code Example
The following PHP code demonstrates the difference in output between the two functions:
$input = "hello world~";
echo urlencode($input); // Output: hello+world%7E (or hello+world~ in newer PHP versions)
echo rawurlencode($input); // Output: hello%20world~When to Use Which
To ensure your application generates valid and predictable URLs, follow these guidelines:
- Use
rawurlencode()when encoding components of a URL path (the parts before the?symbol). For example, if you are dynamic creating folder or file names in a URL path (e.g.,/users/john doe/should become/users/john%20doe/). - Use
urlencode()when generating query string parameters (the parts after the?symbol) specifically designed to mimic legacy HTML form submissions, thoughrawurlencode()is increasingly preferred here as well for modern API compatibility.