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.,-95.712891&sspn=34.512672,45.615234&ie=UTF8&cd=1&z=16

Can be converted to the following.

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 = '';
    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 = '';
    $tinyhandle = fopen($tiny.urlencode(trim($url)), "r");
    $tinyurl = fread($tinyhandle, 26);
    return $tinyurl;


Also, this is a handy function to reverse a TinyURL link:
    $url = explode('.com/', $url);
    $url = ''.$url[1];
    $preview = file_get_contents($url);
    preg_match('/redirecturl" href="(.*)">/', $preview, $matches);
    return $matches[1];
echo reverse_tinyurl("");
It would be cool to get get functions for making URLs with and 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.
@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.
Philip Norton

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


Add new comment

The content of this field is kept private and will not be shown publicly.
13 + 7 =
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.