Shortening URLs from PHP with Bit.ly
Join the DZone community and get the full member experience.Join For Free
I've been looking around for a really simple API that would be a nice place to get started using web services from PHP - and I realised that bit.ly actually fits the bill really well. They have straightforward api docs on google code, and it's also a pretty simple function!
Here's a simple example, using PHP's curl extension, of using the bit.ly API to get a short URL, using PHP (you need an API key, but if you're a registered bit.ly user, you can log in and then find yours at http://bitly.com/a/your_api_key).
$ch = curl_init('http://api.bitly.com/v3/shorten?login=username&apiKey=R_secret&longUrl=http%3A%2F%2Flornajane.net'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); print_r(json_decode($result));
The default format of this API is JSON, which is fine by me as it's simple to work with in PHP! This example just decodes the result into an object and then we print_r() it*. The result is:
stdClass Object ( [status_code] => 200 [status_txt] => OK [data] => stdClass Object ( [long_url] => http://lornajane.net/ [url] => http://bit.ly/nMGNp3 [hash] => nMGNp3 [global_hash] => glZgTN [new_hash] => 1 ) )
The API also provides methods to get the long URL from a short one, validate a short one, and also get all sorts of statistics about a URL that you've shortened using bit.ly. I'm increasingly using bit.ly for shortening URLs, and also for their awesome bundles feature where you can give one link to refer to a list of resources. This comes in really handy for example when I'm giving talks, I can just refer everyone to one link to find everything that I mentioned! Using the API for these kinds of sites mean that we can integrate with systems that already talk to bit.ly, and also avoids us re-inventing a similar service. There are other ways to do this from PHP but since curl is a core extension, this should work on pretty much all installs.
Opinions expressed by DZone contributors are their own.