PHP: urlencode() vs. rawurlencode()

Difference between urlencode() and rawurlencode()

The difference between these two PHP functions is in their return values.

urlencode():

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

rawurlencode():

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

So the difference is that urlencode() encodes space as + and rawurlencode() encodes space as %20. Also since PHP 5.3.0, urlencode() and rawurlencode() also differ in that rawurlencode() does not encode tilde (~), while urlencode() does.

When to use urlencode() and rawurlencode()

Encoding URLs

Every HTTP URL conforms to the following generic URI syntax:

scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  • If you are encoding path segment, use rawurlencode().
  • If you are encoding query component, use urlencode().

The following example demonstrates when to use urlencode() and rawurlencode().


<?php
echo '<a href="http://example.com/'.
    rawurlencode('Sales and Marketing').
    '/search?'.
    'query='.urlencode('Monthly Report').
    '">Click Me</a>';
?>

The above example will output:


<a href="http://example.com/Sales%20and%20Marketing/search?query=Monthly+Report">Click Me</a>

Encoding mailto: links

When encoding mailto: links, spaces must be percent-encoded in email subject and body. That means you need to use rawurlencode() for mailto: links.

For example:


<?php
echo '<a href="mailto:someone@example.com?subject='.
    rawurlencode('Monthly Report').
    '">Click Me</a>';
?>

The above example will output:


<a href="mailto:someone@example.com?subject=Monthly%20Report">Click Me</a>

You May Also Like

Comments

  1. Simple:

    • rawurlencode the path – path is the part before the ? – spaces must be encoded as %20
    • urlencode the query string – Query string is the part after the ? – spaces are better encoded as +

    rawurlencode is more compatible generally.

Leave a Reply

(optional)

This site uses Akismet to reduce spam. Learn how your comment data is processed.