Create The Internet… It's What I Do EVERY Day – Joseph Yancey

16Oct/09N/A0

Bit.ly API function

Everyone knows about the bit.ly url shortening service. I have created a php function to automatically shorten a url passed to it. First, you need to go to bit.ly and signup for an account.  You will need your api key and your username.  With my function, you simply insert your api key and username and it will return a shortened url to you.

If you notice, this function will retry 5 times before it gives up.  That is because bitly will only allow 3 concurrent requests per IP.  My function also will only make the request to bit.ly once per page per session.

  1.  
  2. function getTinyURL($url, $counter = 0){
  3.    global $_SESSION;
  4.  
  5.    if($_WP_SESS['bitlyurl'][$url]){
  6.       return $_SESSION['bitlyurl'][$url];
  7.    }
  8.    $counter++;
  9.    if($counter > 5){
  10.       return $url;
  11.    }
  12.    $login = '';
  13.    $appkey = '';
  14.    $bitly = 'http://api.bit.ly/shorten?version=2.0.1&longUrl='.urlencode($url).'&login=goywp&apiKey='.$appkey.'&format=xml';
  15.    if($response = file_get_contents($bitly)){
  16.    //Debug::printvar($response);
  17.       $xml = simplexml_load_string($response);
  18.       if($xml->results->nodeKeyVal->hash){
  19.          $result = 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
  20.          $_SESSION['bitlyurl'][$url] = $result;
  21.          return $result;
  22.       }else{
  23.          if($xml->results->nodeKeyVal->errorCode == 1206){
  24.             return $url;
  25.          }else{
  26.             return Request::getTinyURL($url, $counter);
  27.          }
  28.       }
  29.    }else{
  30.       return Request::getTinyURL($url, $counter);
  31.    }
  32. }
  33.  
blog comments powered by Disqus

Buy Me a Beer

Well not really a beer
More like a Dr Pepper...