Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Create Bit.ly Short URLs Using PHP

20 Responses »

One of the more popular URL shortening services is Bit.ly. I've showed you how to create short URLs with TinyURL and Is.Gd, so why not show you how to create Bit.ly URLs remotely?

The PHP

/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
	//create the URL
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
	
	//get the url
	//could also use cURL here
	$response = file_get_contents($bitly);
	
	//parse depending on desired format
	if(strtolower($format) == 'json')
	{
		$json = @json_decode($response,true);
		return $json['results'][$url]['shortUrl'];
	}
	else //xml
	{
		$xml = simplexml_load_string($response);
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

/* usage */
$short = make_bitly_url('http://davidwalsh.name','davidwalshblog','R_96acc320c5c423e4f5192e006ff24980','json');
echo 'The short URL is:  '.$short; 

// returns:  http://bit.ly/11Owun

Note that Bit.ly requires you to sign up for an account. Once you have an account, you may attain your login and URL information. I've also created functionality to recieve the shortened URL using JSON or XML.

Happy shortening!

Discussion

  1. tommix
    April 23, 2009 @ 9:05 am

    Hi David, I as always enjoyed your codes they are really helpful… I really interested in Facebook connect… There is no any examples and so… Can you one day make some simple basic example how we can implement it to our sites.. how get data from FB and so on :) Thanks.

  2. April 23, 2009 @ 9:13 am

    Thanks! There are some PHP API info at: http://to.ly/api_info.php

  3. April 23, 2009 @ 10:30 am

    Not sure if there is anything that can be done about this, but the xml rss feed does not show the code in a friendly format within Outlook. But other then that.. This is great!!! Thanks a lot David!

  4. April 23, 2009 @ 12:53 pm

    I played around with this function a bit and added cURL into it.

    Also, if you want the shortened URL to show up in your history on bit.ly (which is useful for statistics and the like), you have to add ‘&history=1′ to the URL.

    I added that parameter to the function (along with cURL), for anyone who’s interested:

    function make_bitly_url($url, $login, $appkey, $format=’xml’, $history=1, $version=’2.0.1′)
    {
    //create the URL
    $bitly = ‘http://api.bit.ly/shorten’;
    $param = ‘version=’.$version.’&longUrl=’.urlencode($url).’&login=’
    .$login.’&apiKey=’.$appkey.’&format=’.$format.’&history=’.$history;

    //get the url
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $bitly . “?” . $param);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);

    //parse depending on desired format
    if(strtolower($format) == ‘json’) {
    $json = @json_decode($response,true);
    return $json['results'][$url]['shortUrl'];
    } else {
    $xml = simplexml_load_string($response);
    return ‘http://bit.ly/’.$xml->results->nodeKeyVal->hash;
    }
    }

    Great post, David!

  5. david
    April 24, 2009 @ 4:13 am

    I wonder why you need to set the format? Shouldn’t that be handled internally?

    With the recent discussion about url shortening services is it a good thing you present a function for one of these services?

  6. fabian beiner
    April 24, 2009 @ 6:47 am

    I create a small PHP class: http://rafb.net/p/2LLWwg88.html – maybe someone can use it…

  7. fabian beiner
    April 24, 2009 @ 6:49 am

    Oops, should be “private $strApiKey, $strLogin, $strUrl, $bolCurl = false;” :( There might be some more problems, I wrote that while eating my soup ;)

  8. fabian beiner
    April 24, 2009 @ 7:07 am

    Gosh, once again, this time with working link (hopefully): http://rafb.net/p/9RcZDk98.html

  9. May 28, 2009 @ 1:43 pm

    Thanks for the great code. I’ll try to do something cool with it.
    Thanks again and keep up the great work.

    Don

  10. August 29, 2009 @ 5:02 am

    Great function, combined with Jason Lengstorf’s fixes makes the best of this functionality that lies around on the web. Short and effective.

  11. November 12, 2009 @ 3:31 pm

    Wow! You saved my morning w. this script. Thank you. Keep up the good work.

  12. November 18, 2009 @ 7:49 pm

    Great stuff David,

    I would suggest tweaking the code as the following to make it more tolerant of network timeouts.

    Cheers

    Line 9:
    $response = @file_get_contents($bitly);
    if ($response == false) return false /* or something else */

  13. November 21, 2009 @ 3:18 pm

    Thanks a lot for your code! I’m using this on a WordPress project and it’s far better and slimmer than using a bloated social media plugin. I just put a direct link to Twitter and add in the short link with it. Works great.

  14. January 12, 2010 @ 8:46 pm

    Hi, thanks for sharing this tips. I’m using it. thanks again.
    Regards

  15. February 20, 2010 @ 1:04 am

    Really useful and good code david! I am going to use it :)

  16. February 21, 2010 @ 1:24 pm

    @Jason Lengstorf:

    Thanks for sharing the cURL version Jason!

  17. March 25, 2010 @ 8:57 pm

    hello, please help me, i have a problem with file_get_contents….
    my server don’t allow this …

    thx2u
    Voisin

  18. April 6, 2010 @ 9:09 pm

    I modified this function to make it compliant with the v3 version of the bit.ly API, you can find the article over here: http://www.bumpershine.com/making-short-wordpress-urls-with-bit-ly-and-php. I also added in an example of how I am using it shorten wordpress URLs specifically.

  19. klebson
    July 28, 2010 @ 6:53 am

    What if the bit.ly system returns an error? or even returns nothing (due timeout or serverdown) ?
    How can I catch the error?

  20. ice
    August 31, 2010 @ 3:15 pm

    Thanks a lot for the very useful code. Great job.

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!