Shortening multiple URLs with jQuery, PHP, picolisp and bit.ly

I just managed to create a function that will automatically find all URLs in the text in a text area and replace them with shortened URLs by way of bit.ly and I thought I’d share it.

Let’s start with the jQuery:

$("#bitly").click(function(){
  var twMsg = $("#tw_update_input").val();
  var urls = twMsg.match(/http:\/\/\S+/gim);
  $.post("@shortenUrls", {urls: $.toJSON(urls)}, function(res){
    var result = $.evalJSON(res);
    $.each(urls, function(){
      var regex = new RegExp(this, "igm");
      twMsg = twMsg.replace(regex, result.results[ this ].shortUrl);
    });
    $("#tw_update_input").val(twMsg);
    $("#tw_words_left").html( 140 - twMsg.length );
  });
});

1.) A DIV with the id “bitly” is first clicked.
2.) We store the current contents of the text area in twMsg. The use of tw here and there is due to the fact that the message will eventually be submitted to Twitter.
3.) We get all the URLs in the message and store them in urls. Note that the regex is pretty simple, it won’t catch stuff like http://domain.com,. That comma will end up in the result.
4.) We post (by way of AJAX) the array of matches as a JSON encoded string, to a pico lisp script (more on that later).
5.) We get the JSON result back (this is the original JSON result as it is returned from bit.ly) and promptly decode it.
6.) We then loop through each of he original URLs because they are used as keys in the bit.ly result object so we need them in order to be able to map them against their short counterparts.
7.) We replace each url in turn with the help of the bit.ly results.
8.) We replace the contents of the text are with the new content containing the shortened URLs and update the 140 character counter. This is a Twitter post remember?

Let’s move on to the PHP:

$context = stream_context_create(array( 
    'http' => array( 
        'timeout' => 10
        ) 
    ) 
); 

array_shift($_SERVER['argv']);

$url = "http://api.bit.ly/shorten?version=2.0.1&login=my_login&apiKey=my_api_key";

foreach($_SERVER['argv'] as $u)
	$url .= "&longUrl=".urlencode($u);

echo file_get_contents($url, 0, $context);

We use file_get_contents to get the result, using a timeout of 10 seconds. Note that this CLI script will be called as a system call where the first argument is the name of the script of course, therefore we shift it off the arguments array. We then add one or more longUrls to the bit.ly GET string. I think this is a nice feature so you don’t have to do repeat calls if you want to shorten several URLs at once. Note that the URLs need to be URL encoded.

Finally we echo the result.

And finally the intermediary picolisp code:

(de shortenUrls ()
   (usrQuit)
   (httpHead "text/plain; charset=utf-8")
   (ht:Out T (prin (in (append (list "php" "bitly.php") (from> '+Json (req 'urls))) (till NIL T)))))

We call the bitly.php script which was explained above with a list of argument URLs, this we manage through the use of append which will turn the JSON decoded list of urls and the “php” + “bitly.php” list into one. The JSON response from bit.ly will be returned as is, we convert it in the jQuery code that was explained at the top.

Related Posts

Tags: , , , , , , ,