PHP Function To Get TinyURL

TinyURL is a service where you can convert a long URL string to a really small one. For instance, the following URL, which points to the Googleplex on Google Maps.

http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=googleplex&sll=37.579413,-95.712891&sspn=34.512672,45.615234&ie=UTF8&cd=1&z=16

Can be converted to the following.

http://tinyurl.com/qpkor2

This is perfect for posting to Twitter or similar microblogging platforms as it saves lots of character space.

Luckily, TinyURL provides an API, so automatically generating URLs for your application is quite easy. The following functions both do the same thing, return a converted URL, but the first uses file_get_contents() and the second uses fopen() and fread(). Which one you use is up to you. The both also prepare the URL before sending it off to TinyURL so they the URL doesn't break when users try and click on it.

function tinyUrl($url){
    $tiny = 'http://tinyurl.com/api-create.php?url=';
    return file_get_contents($tiny.urlencode(trim($url)));
}

Note that the API returns a 25byte string, so getting the first 26 bytes will cover future changes in case TinyUrl increase the number of characters returned in the future.

function tinyUrl($url){
    $tiny = 'http://tinyurl.com/api-create.php?url=';
    $tinyhandle = fopen($tiny.urlencode(trim($url)), "r");
    $tinyurl = fread($tinyhandle, 26);
    fclose($tinyhandle);
    return $tinyurl;
}

Comments

Also, this is a handy function to reverse a TinyURL link:
reverse_tinyurl($url){
 
    $url = explode('.com/', $url);
 
    $url = 'http://preview.tinyurl.com/'.$url[1];
 
    $preview = file_get_contents($url);
 
    preg_match('/redirecturl" href="(.*)">/', $preview, $matches);
 
    return $matches[1];
 
}
 
echo reverse_tinyurl("http://tinyurl.com/2s4hz8");
It would be cool to get get functions for making URLs with bit.ly and tr.im as they seem to be the most popular ones now. I haven't seen a TinyURL for months now. With the likes of Twitter, the shorter ones are always preferred over the longer TinyURL ones.
Permalink
@Jamie - Thanks! I was going to create that function in by blog post tomorrow. :P Good point about the other URL sites, I think a series of posts about each one might be in order.
Name
Philip Norton
Permalink

Thanks a lot - your answer solved all my problems after several days struggling.

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.