Simple shorten url using bit.ly and php

Inspired by the simple tweet to twitter function by Fabian Potencier I have built a stupidly simple url shorter for bit.ly. Something you are probably going to want to do if you are sending tweets via PHP.

function shorten($url, $login, $apikey)
{
  $api_url = "http://api.bit.ly/shorten?version=2.0.1&
                    longUrl=".urlencode($url)."&login=".$login."&
                    apiKey=".$apikey;
  $ret = file_get_contents($api_url);
  $data = json_decode($ret);
  if($data instanceof stdClass && property_exists($data, "errorCode") && $data->errorCode==0)
  {
    foreach($data->results as $result)
    {
      if(isset($result->shortUrl))
      {
        return $result->shortUrl;
      }
    }
  }
  return $url;
}

In the application where I am using this function I have defined the login name and api key as constants, so you can do away with 2 function calls.

Also handily it returns the original url if bit.ly fails.

Post a Comment

Your email address is never published nor shared. Required fields are marked *

Ready to talk?

Whether you want to create a new digital product or make an existing one even better, we'd love to talk it through.

Get in touch