Skip to content

Instantly share code, notes, and snippets.

@bfintal
Created January 20, 2013 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfintal/4577329 to your computer and use it in GitHub Desktop.
Save bfintal/4577329 to your computer and use it in GitHub Desktop.
So I've found a ton of Goo.gl API shortener classes out there but nothing worked for me (maybe because of wrong cURL options or outdated urls, etc). This one is simple and works nicely. The function doesn't need any API keys and returns the original url if curl isn't present.
class BFIGoogleUrl {
public static function shorten($url) {
if (!function_exists('curl_init'))
return $url;
$api = 'https://www.googleapis.com/urlshortener/v1/url?';
$data_string = '{"longUrl":"'.$url.'"}';
# Initialize cURL
$ch = curl_init();
# Set our default target URL
curl_setopt($ch, CURLOPT_URL, $api);
# We don't want the return data to be directly outputted, so set RETURNTRANSFER to true
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Set cURL options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30"); // from timthumb
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// get the shortened url
$ret = json_decode(curl_exec($ch))->id;
# Close the curl handle
curl_close($ch);
$ch = null;
return $ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment