Using the Tinyurl API

Lately I’ve had a need to use the Tinyurl.com API. The API has been useful 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()

PHP
1
2
3
4
5
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 http://tinyurl.com/ the first part of the url to the code also so the random key function takes a little more code.

PHP
1
2
3
4
5
function randomKey($url){
$key = file_get_contents('http://tinyurl.com/api-create.php?url='.$url);
$key = str_replace('http://tinyurl.com/', '', $key);
return $key;
}
PHP
TAGS: , ,
No Comments