URL Encoding: Why urlencode() Doesn't Produce %20 for Spaces
The expectation that PHP's urlencode() function will automatically replace spaces with %20 is a common misconception, often stemming from how browsers historically handled form submissions versus how the actual encoding standard works. When you run $str = "What happens here?"; echo urlencode($str);, you get What+happens+here%3F. The spaces are represented as + signs, not %20. This isn't a bug; it is a specific behavior of the application/x-www-form-urlencoded content type, which is the standard for HTML forms.
In this encoding scheme, a space character serves two distinct roles depending on context. The plus sign (+) is technically a valid representation for a space, but strictly speaking, %20 is the percent-encoded equivalent found in RFC 3986. While urlencode() prioritizes using + to save bandwidth and maintain compatibility with legacy form parsers, it leaves non-alphanumeric characters like the question mark (?) as %3F.
If you strictly require spaces to appear as %20 instead of +, you must manually replace the characters after encoding. This is a straightforward string manipulation task:
$urlEncoded = urlencode($str);
$strictUrlEncoded = str_replace(['+', '%2B', '%7E'], ['%20', '%2B', '%7E'], $urlEncoded);
echo $strictUrlEncoded;
// Output: What%20happens%20here%3F
However, before jumping into manual string replacement, it is crucial to understand why you want this. The + character is semantically equivalent to a space in the context of HTML forms. If your goal is simply to prepare a query string for passing to a server via an HTTP GET request, using urlencode() directly is usually sufficient. Most parsers treat + and %20 interchangeably when decoding the final URL.
There are scenarios where strict adherence to %20 is necessary. One such case involves URLs containing special characters that might be confused by naive parsers, or when constructing a URI fragment identifier. If you need to build a full URL string that will be displayed in a browser's address bar or passed directly into another API client that strictly forbids + (even though they are technically equivalent), using rawurlencode() is often the safer bet for non-form data.
$str = "What happens here?";
echo rawurlencode($str);
// Output: What%20happens%20here%3F
The function rawurlencode() differs from urlencode() in that it encodes spaces exclusively as %20 and does not replace them with +. It also encodes a wider range of characters, including those that are safe for inclusion in a URL path but might be interpreted differently in a query string. This makes rawurlencode() the preferred choice when constructing the path component of a URL or when sending data to APIs like GitHub or GitLab that expect strict RFC 3986 compliance for path segments.
The trade-off lies in performance and compatibility. Using rawurlencode() on large strings requires slightly more CPU cycles than urlencode(), but modern servers handle this negligible difference without issue. The real pitfall is assuming these functions are interchangeable across all contexts. If you encode a query string with rawurlencode() and the receiving end expects a form-encoded value where + means space, you might encounter parsing issues if the receiver strictly distinguishes between them.
Furthermore, be mindful of Unicode characters. Both urlencode() and rawurlencode() handle UTF-8 correctly by converting multi-byte characters into their percent-encoded hex representations (e.g., an emoji becomes %F0%9F%98%80). However, rawurlencode() is generally more robust for general URL construction because it avoids the + ambiguity entirely.
If you are working within a Laravel application, the framework handles this complexity by providing helper methods that abstract these details away. You can use Illuminate\Support\HtmlString or specific string helpers, but for pure URL query building, sticking to rawurlencode() ensures your spaces never become +, eliminating any potential ambiguity in cross-platform API integrations.
Ultimately, the choice depends on whether you are building a form submission payload or constructing a generic URI. For forms, urlencode() is standard and efficient. For general URLs, paths, or strict API compliance, rawurlencode() provides the %20 representation out of the box, sparing you from manual string replacement logic.
