March 8, 2011

URL Shortening with Goo.gl

Google has been offering their URL shortening service for some time now, but for those of you trying to follow along with the official documentation here: http://code.google.com/apis/urlshortener/v1/getting_started.html you’ll have noticed that it’s not quite working. Here’s how to get url shortening up and running

1 2 3 4 5 6 7 8 9 10 11 12 13 
<?php
$longUrl = 'http://facebook.com;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://goo.gl/api/shorten');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'security_token=null&url='.$longUrl);
$content = curl_exec($ch);
curl_close($ch);
echo json_encode($content);
?>

If you’re getting any errors about curl not being enabled, simply pop open your php.ini file and look for this line: ;extension=php_curl.dll Then just delete the ‘;’ at the front. Don’t forget to restart your server for the new extension to come into effect.