Archive for the ‘PHP’ Category

Using the Tinyurl API

Tuesday, May 5th, 2009

Lately I’ve had a need to use the Tinyurl.com API. The API has been usefull for a couple of things since I started using it.

Shortening URL’s

This is obviously the intended purpose of the Tinyurl API. With a very simple function you can shorten urls very easily. This function passes the url to the Tinyurl API which shrinks it and then it is pulled back using file_get_contents()

function shrinkUrl($url){
    $url = file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
    return $url;
}
$tinyurl = shrinkUrl('http://www.ninnypants.com');// equal to http://tinyurl.com/6lbwc4

Generating a Random Key

The Tinyurl API can also be used to generate a random key specific to the information you pass in. As long as you don’t pass in a url Tinyurl will only return the the code at the end of the url (6lbwc4) The service now attaches the the first part of the url to the code also so the random key function takes a little more code.

function randomKey($url){
    $key = file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
    $key = str_replace('http://tinyurl.com/', '', $key);
    return $key;
}