Create Bit.ly Short URLs Using PHP

By on  

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?


/* 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!

Track.js Error Reporting

Upcoming Events

Recent Features

  • How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • 5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • MooTools 1.2 Image Protector: dwProtector

    Image protection is a hot topic on the net these days, and why shouldn't it be? If you spent two hours designing an awesome graphic, would you want it ripped of in matter of seconds? Hell no! That's why I've created an image...

  • pointer Media Query

    As more devices emerge and differences in device interaction are implemented, the more important good CSS code will become.  In order to write good CSS, we need some indicator about device capabilities.  We've used CSS media queries thus far, with checks for max-width and pixel ratios....


  1. Tommix

    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. Thanks! There are some PHP API info at: http://to.ly/api_info.php

  3. 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. 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='
        //get the url
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $bitly . "?" . $param);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($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!

    • Thanks Jason, I found your example more effective and useful. I’m going to use it on my next project with your reference.

  5. david

    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

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

  7. Fabian Beiner

    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

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

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


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

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

  12. Great stuff David,

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


    Line 9:

    $response = @file_get_contents($bitly);
    if ($response == false) return false /* or something else */
  13. 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. Hi, thanks for sharing this tips. I’m using it. thanks again.

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

  16. @Jason Lengstorf:

    Thanks for sharing the cURL version Jason!

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


  18. 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

    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

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

  21. Great code, does what it says on the tin. Thanks!

  22. 2 Questions:

    1. Will this code catch and shorten ALL links from sharing plugings, etc?
    3. Where do I put the code? (functions.php, custom.css)

    Just looking for a “catch all” for any links leaving my site for sharing.

    Be kind to the newb

  23. Hi,

    This has stopped working since past 3-4 days. We have always been using your system but just a few days ago noticed it is not working anymore.

  24. Is it possible to use https instead of http://api.bit.ly ?

  25. I’m new to bit.ly – is it possible to create bit.ly links from a spreadsheet of URLs or a feedburner RSS Feed?

  26. mujaffar

    Great post david

    You saved my lots of time

    Worked fine for me

  27. adrian465

    Thanks! I have problems with urls with & in it. The shortner make &amp outta it.

  28. adrian465

    I mean &amp

  29. Thanks for the example. I was actually looking for examples of how to generate bit.ly within Titanium Studio for mobile apps. I found your example instead. I think I can use this, though.

  30. Gloria

    I’m having a hard time shortening my links with bitly. I know I am doing something wrong, but I don’t know what….
    I copy and paste the link to the “shorten link” box. It does change it and it shows under the box with the short form. If I leave the page and try to get back to use it, it’s gone. So I do it all over again and the same thing. I signed up with them, and it shows on the page I’m logged on.
    Is there a place where you can save the shorten links?
    I understand you can check the number of clicks on each link. I just don’t know how to save the links.
    I’m very “computer challenge”, so please don’t be to technical
    Also I bundle two links, and I can’t even find them…. Sorry this is embarrassing… I tried to follow their directions but they are kind of confusing to me.

  31. The post is really useful. It helps you make short urls for you 100-1000 word urls which looks really ugly and hard to paste on a sheet when you mail it.

  32. Pavy

    as per the code you have give here, I see the version is harcoded to ‘2.0.1’.. IS der any chance that we can have this version updated automatically?

  33. ProGab

    Thank you very much for this awesome function. I recommend specifying the login and appkey inside of function and call the function with only the url.


    function make_bitly_url($url,$login = 'yourlogin',$appkey = 'yourappkey',$format = 'xml',$version = '2.0.1')


  34. Hi, I am trying to add this function to my website, but when I run the file from my webhosting.
    All I get is the displayed echo “The short URL is: ” with no short url…
    Can anyone help !

  35. Armin

    Sorry if I ask silly question, but how can I create a button for my site which run this script?
    I’d like to have a button “Copy Page ShortURL” in each page. I think I have to insert this code in footer but how should I create the button to load and run it?

  36. Cheers!

    It really helps, thanks God I found this post of yours…

    Thanks :D

  37. Hello,
    Before using this script, you should get your own API infos..
    otherwise, the demo will not work..
    thanks for sharing that script,
    i was very usefull for my project

  38. karthiga

    When they click on tweet button, twitter box platform will popup and user can write or edit something before tweet

    Twitter button code:

    <a href="https://twitter.com/share" style="padding: 0px; margin: 0px; height: 40px;"class="twitter-share-button" data-url="" data-text="Check this out!" data-via="TeenLeakss">Tweet
    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

    the mention above code only i used. it is work in while highlighting twitter button the link should be shown like shorturl.But it doesn’t seems to be tweet for twitter.

    How to fix this?

  39. Johann

    It’s even easier now !! With the V3 you can directly have your link by using the text format.


    More info here : http://dev.bitly.com/links.html#v3_shorten

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...

  • Serve a Directory with PHP

    Many developers have a giggle at PHP, even looking down at the language, but let's be honest:  most of our blogs are powered by it (WordPress) and it's a great language to dabble around with.  I cut my teeth on PHP, though I prefer to avoid PHP these days. But...

  • Tips you can Use to Build an Excellent eCommerce Experience

    There are many reasons to build a good eCommerce experience if you are planning to build an eCommerce website. Visitors can place items in their cart and leave your site without making a purchase. In fact, three out of every four of them will do so....