Reverse TinyURL, bit.ly, is.gd, and more with PHP and cURL

Feb 23, 2009 by     8 Comments    Posted under: Hacks, Tech

I’m working on a new project that requires me to take URLs made from url shorteners like tinyurl.com, is.gd, and bit.ly, and reverse them back to their full form.

There are a few online services that do this for you already (even a funny one that takes a small URL and makes it huge), and some of the shortners–like tinyurl–have a few back-door methods to let you reverse their URLs. I needed one I could place in a PHP script–and one that didn’t have the overhead of some I had found across the web.

The PHP code below will take a shortened URL and return you its full form. This has worked on every short-url I’ve tried–but if you find one it stumbles on, please let me know.

See a live demonstration

Code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://bit.ly/aKAuf");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 
$result = curl_exec($ch);
 
if (preg_match("/Location\:/","$result")) {
$url = explode("Location: ",$result);
$reversed_url = explode("\r",$url[1]);
echo $reversed_url[0];
} else {
print_r($result);
}
  • Ben

    This is great, I’ve been searching for something like this. However, is there a way for it to automatically convert a tinyurl that’s already posted on a page replacing it with the true url?

  • http://www.asaami.com Umar

    Hi Ben,

    Can you elaborate your question plz. I want to see if I can help yaa.

    Regards
    Umar

  • Will Knot B. Revealed Snr.

    I tried the demo, it works wonderfully, I love it :)

  • Will Knot B. Revealed Snr.

    I tried the demo, it works wonderfully, I love it :)

  • Will Knot B. Revealed Snr.

    I tried the demo, it works wonderfully, I love it :)

  • Will Knot B. Revealed Snr.

    Also meant to say thank you for sharing :)

  • Will Knot B. Revealed Snr.

    Also meant to say thank you for sharing :)

  • Will Knot B. Revealed Snr.

    Also meant to say thank you for sharing :)