Get the Real URL of a Tiny URL in PHP

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:

<?php
//$url = "http://tinyurl.com/1c2";
$url = "http://goo.gl/NQoZko";
$headers = get_headers($url);
<br>
foreach ($headers as $key => $value) {
    if (strpos($value,'ocation:') !== false) {
        $url = $headers[$key]; 
    }
}
<br>
$url = str_replace('Location: ', '', $url);
$url = str_replace('location: ', '', $url);
<br>
echo $url;
?>

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!

1 Comment

  • When I originally commented I appear to have clicked on the -Notify
    me when new comments are added- checkbox and from now
    on every time a comment is added I receive four emails with the same comment.
    Is there a way you are able to remove me from that service?
    Kudos!

Leave A Comment

Your email address will not be published. Required fields are marked *