[ACCEPTED]-Find where a t.co link goes to-url-shortener

Accepted answer
Score: 20

I would stay away from external APIs over 8 which you have no control. That will simply 7 introduce a dependency into your application 6 that is a potential point of failure, and 5 could cost you money to use.

CURL can do 4 this quite nicely. Here's how I did it in 3 PHP:

function unshorten_url($url) {
  $ch = curl_init($url);
  curl_setopt_array($ch, array(
    CURLOPT_FOLLOWLOCATION => TRUE,  // the magic sauce
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_SSL_VERIFYHOST => FALSE, // suppress certain SSL errors
    CURLOPT_SSL_VERIFYPEER => FALSE, 
  ));
  curl_exec($ch); 
  return curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
}

I'm sure this could be adapted to other 2 languages or even scripted with the curl command 1 on UNIXy systems.

http://jonathonhill.net/2012-05-18/unshorten-urls-with-php-and-curl/

Score: 8

If you want to do it from the command line, curl's 5 verbose option comes to the rescue:

curl -v <url>

gives 4 you the HTTP reply. For t.co it seems to 3 give you an HTTP/301 reply (permanently 2 moved). Then, there's a Location field, which 1 points to the URL behind the shortened one.

Score: 7

curl -s -o /dev/null --head -w "%{url_effective}\n" -L "https://t.co/6e7LFNBv"

  • --head or -I only downloads HTTP headers
  • -w or --write-out prints the specified string after the output
  • -L or --location follows location headers

0

Score: 3

Here is a Python solution.

import urllib2

class HeadRequest(urllib2.Request):
    def get_method(self): return "HEAD"

def get_real(url):
    res = urllib2.urlopen(HeadRequest(url))
    return res.geturl()

Tested with an 3 actual twitter t.co link:

url = "http://t.co/yla4TZys"
expanded = get_real(url)

expanded = http://twitter.com/shanselman/status/276958062156320768/photo/1

Wrap 2 it up with a try-except and you are good 1 to go.

Score: 1

Another Python solution, this time relying 2 on the requests module instead of urllib2 1 (and all the rest of those libraries):

#!/usr/bin/env python

import requests

shorturl = raw_input("Enter the shortened URL in its entirety: ")
r = requests.get(shorturl)

print("""
The shortened URL forwards to:

    %s
""" % r.url)

More Related questions