PHP tip: URLENCODE vs RAWURLENCODE
Bookmark and Share

PHP tip: URLENCODE vs RAWURLENCODE - A PHP example of when to use rawurlencode instead of urlencode

There are these boring syntax definitions and documents called RFC

RFC stands for Request For Comment

In the computer world, it's a method for defining interoptibility.

RAWURLENCODE follows RFC 3986
This is general syntax of a URI

URLENCODE follows RFC 1738
This is general syntax of a URL

NOTE (un-related) Difference between a URL vs. URI vs URN found here

The main difference between the two is the encoding of a [SPACE]

URLENCODE - encodes a space as a plus sign '+'

RAWURLENCODE - encodes a space as '%20'

Example usage

Let's say you have an anchor tag for a contact form for an email (mailto:)

You want to populate subject line and the body of the email.

PHP urlencode would produce something like this: 
<a href="mailto:notreal@phphaven.com?body=Hi+I+would+like+to+contact+you+about+this+opportunity&subject=New+Opportunity">Contact us about this</a>

PHP rawurlencode would produce something like this: 
<a href="mailto:notreal@phphaven.com?body=Hi%20I%20would%20like%20to%20contact%20you%20about%20this%20opportunity&subject=New%20Opportunity">Contact us about this</a>

Why use rawurlencode?
In this example (although a bit dated), we want the default mail program to open on the user's machine (client) and populate the to, subject, and body.

If we use urlencode, the body and subject will populate with the '+' plus signs.

If we use rawurlencode, the body and subject will populate correctly and your link will be valid as of RFC 3986

Nuff said.
=D
Recent Comments