PHP URL Shortening


A current Twitter related project involves quite a few URLs and because Twitter limits you to only 140 characters per post shortening a link can be very rewarding.

There are a multitude of URL shortening services on the internet and whilst perhaps not producing the shortest links, TinyURL.com requires no account in order to use it via PHP which makes for a very simple query:
function getTinyUrl($url) {
return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}

bit.ly is another popular URL shortener, however it does require an easily obtainable API key. The code is below:
function getBitly($url) {
$query = file_get_contents("http://api.bit.ly/v3/shorten?login=YOUR_LOGIN&;apiKey=YOUR_APIKEY&longUrl=".$url."&format=xml");
$element = new SimpleXmlElement($query);
$bitlyurl = $element->data->url;
if($bitlyurl){
return $bitlyurl;
} else {
return '0';
}
}

Don’t forget to change YOUR_LOGIN and YOUR_APIKEY to your own values. I’m sure you don’t need any help with usage, but as always comment if you have any issues.

Leave a Comment

Your email address will not be published. Required fields are marked *