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:

Technical Standards

The difference in behavior stems from the historical Internet standards they implement:

Character Comparison

Beyond spaces, there are minor differences in how older versions of PHP handled other characters like the tilde (~).

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: