Tag Archive: tiny url

Get the Real URL of a Tiny URL in PHP

October 21, 2013

A while back I set up a website, songdump.com, that allows me to post Youtube videos of songs I really like. But, I’m lazy, and I wanted to use the least amount of effort to accomplish this.

I ended up setting up a If This Then That recipe for the hashtag “#songdump.” So, whenever I share a song through Twitter, IFTTT grabs the URL and through some other scripts, retrieves all the necessary info I need for that video, and posts it in WordPress (where the data is called from).

Problem is, when you share something on Twitter, it’s often a TinyURL which makes it a lot harder to retrieve info from. Luckily, we can use the PHP function “get_headers()” to accomplish this.

Tiny URL’s come in a lot of different forms, so I used this method because alternatives often had you filter based on a predetermined set of base URLs. That did me no good.

Here’s the script:

Let’s recap what’s happening line by line here –

  1. Storing our tiny URL as a variable, showing 2 examples
  2. Using the get_headers() function to retrieve the location of our URL
  3. This returns an array, and one of values in that array is our URL. It begins with “Location:” or is some cases “location:”. Feel free to use print_r($headers) function before this to learn all of get_headers() returned values
  4. The key for this value is often in different orders (which is why I provided 2 URLs as examples). We will loop through every value to see if it contains “ocation:” (because as I said, sometimes it’s uppercase, sometimes it’s lowercase) and then return that key.
  5. Once we find the right array object, we get its value and store it as a variable.
  6. Using a string replace function, we remove the actual “Location” label. I do this twice, uppercase and lowercase, because it can get returned either way in some cases.
  7. Then we print out the real URL!

Hope that helps! Happy coding!