If you use service like Twitter where you only get a limited number of characters to post or if you are just sick of dealing with unruly long urls you might be familliar with url shortening services such as Bit.ly.
I personally like them because of they offer a nice API and statistics all for free. It is a pretty quick service too. You can generate hundreds of URLs in just a few seconds. All you have to do is register and you get a username and API key which you will need in the following section.
Here is the code … As you can see I only implemented the shorten for now but I will probably add some of the other stuff later. For some reason WP won’t let me post curl_exec( so be sure to remove the extra character.
class bitly { /** * A PHP class to utilize the bitly API * through the Bitly API. Handles: * - Shorten * * Requires PHP5, CURL, JSON and a Bitly account http://bit.ly/ * * Bitly API documentation: http://code.google.com/p/bitly-api/wiki/ApiDocumentation */ protected $appkey; protected $login; protected $version; /** * Contruct the Bitly Class * * @param string, your Bitly account key * @param string, your Bitly account login */ public function __construct($login, $appkey, $version='2.0.1') { $this->login = $login; $this->appkey = $appkey; $this->version = $version; } /** * Retrieve a shortened URL * * @param string, url to shorten * @param string, version of Bitly to use */ public function shorten($url) { //create the URL $api_url = 'http://api.bit.ly/shorten?version='.$this->version.'&longUrl='.urlencode($url).'&format=xml&login='.$this->login.'&apiKey='.$this->appkey; //call the API $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $api_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_ex_ec($curl); curl_close($curl); //parse the XML response and return the url $xml_object = new SimpleXMLElement($response); return $xml_object->results->nodeKeyVal->shortUrl; } }
If you want to use this in CakePHP … you will want to do something like this.
Put this line before the class … I actually use this in a helper since this is a view level class
App::import('Vendor','Bitly', array("file" => "bitly/bitly.class.php"));
Now you can just invoke it in one of your functions somewhere with two simple calls!
$bitly = new Bitly('username', 'your_API_key_here'); $short_url = $bitly->shorten($long_url);
Simple as that … oh and one more thing. Be sure to have CURL installed else this won’t work.