PHP Tutorial: Raw Encoding
|June 14, 2012||Posted by Greg Bulmash under PHP|
Today's tip is quick and dirty. I spent my time mulling over the Observer pattern and a story about a royal wedding, but it just wouldn't come together before bedtime.
So today's tip is about
Encoding is useful when you need to compose a GET URL that has parameters in it containing characters that are technically illegal to use in a URL (like spaces) or that might mess up your query string (like ampersands and question marks). This is where
urlencode() always seemed to come in handy.
$customername = "Ted Fischer"; $customeraddress = "124 Main St."; $closestXstreets = "Main & Vincent"; $displayclientlocationURL = "http://spgulhankmeder.com/mapit?name=" . urlencode($customername). "&address=" . urlencode($customeraddress) . "&xstreets=" . urlencode($closestXstreets); echo "<a href=\"$displayclientlocationURL\">Map it</a>";
<a href="http://spgulhankmeder.com/mapit?name=Ted+Fischer&address=124+Main+St.&xstreets=Main+%26+Vincent">Map it</a>
All the spaces are converted to plusses and the ampersand that's part of content instead of control has been converted to %26.
That might be okay, but I've found out the hard way that not every receiving server is going to convert those pluses back to spaces. Some don't back-convert them, particularly if they're not running PHP. See the spec in RFC 3986 says that spaces should be rendered as
%20, not as
+. If you're in a mixed environment and can't be sure the receiving server will treat pluses as spaces, using
rawurlencode will get you the following:
<a href="http://spgulhankmeder.com/mapit?name=Ted%20Fischer&address=124%20Main%20St.&xstreets=Main%20%26%20Vincent">Map it</a>
And that will be understood and decoded properly in more places in my experience. I've known about urlencode() for a while now, but it's raw version is new to me and now I'm sharing it.