PHP urlencode Tips & Tricks

Posted on

If you hate reading…

When you use urlencode on a get parameter in the url, you do not need to use urldecode on the value when you retrieve it in your script. PHP automatically performs a url decode for you.

I was recently writing a php script to verify an email address after a user signs up on a website. It actually took me quite a while to sort out a bug that I encountered. I’m writing this post today in hopes that my trial and error will help you in the future to avoid this situation.

The Objective

I needed to send a hash of the users email and a timestamp using a query variable from an auto generated email. The user would click the link and be redirected to the website where the site would process the hash and verify the user account. Simple enough, right? As it turned out, not really.

  • Generate hash from email and timestamp
  • Send email with email verification link that includes a urlencode‘ed hash
  • User clicks link from inside email
  • Hash is processed
  • User is found in the database using information from hash
  • User is verified and then logged in

The Problem

Everything runs smoothly until the user clicks the link inside their email. The hash is urlencoded by using the php urlencode() function. When I process the hash, I was url decoding it using the php urldecode() function. After that, I was splitting the hash using php explode with a colon as the delimiter. I should have gotten back an array with two values, an email and a timestamp. Instead, I got an error (undefined index).

I was supposed to have gotten the email and timestamp back so I could run a query against the database to find the user that had the pertinent data in their user row.

The Solution

I found out that when you get a parameter from the url using $_GET, php automatically uses urldecode on the value. With this not known to me at the time, I was running urldecode on a value that was already decoded. In essence, I was, obliviously, url decoding twice. This was spitting out some weird characters such as boxes, triangles and question marks.

Long story short, you do not need to use urldecode on $_GET variables. At least, that is what I got out of the ordeal. Please correct me if I am wrong.

Thanks and as always, Happy Coding!