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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?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 –
- Storing our tiny URL as a variable, showing 2 examples
- Using the
get_headers()
function to retrieve the location of our URL - 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 ofget_headers()
returned values - 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.
- Once we find the right array object, we get its value and store it as a variable.
- 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.
- Then we print out the real URL!
Hope that helps! Happy coding!