Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Created June 16, 2012 16:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MikeRogers0/2941923 to your computer and use it in GitHub Desktop.
Save MikeRogers0/2941923 to your computer and use it in GitHub Desktop.
Shorten URLs using the Google URL Shortener and PHP
<?php
// Coded by Mike Rogers (http://www.fullondesign.co.uk/) 1st October 2010.
function shorten($url, $qr=NULL){
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
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='.urlencode($url));
$results = curl_exec($ch);
$headerInfo = curl_getinfo($ch);
curl_close($ch);
if ($headerInfo['http_code'] === 201){ // HTTP Code 201 = Created
$results = json_decode($results);
if(isset($results->short_url)){
$qr = !is_null($qr)?'.qr':'';
return $results->short_url.$qr;
}
return FALSE;
}
return FALSE;
}
trigger_error("cURL required to shorten URLs.", E_USER_WARNING); // Show the user a neat error.
return FALSE;
}
// Example: Just the Short URL
echo shorten('http://www.google.com/');
// Example: Give the Short Code URL and image it.
$qrURL = shorten('http://www.google.com/', TRUE);
echo '<img src="'.$qrURL.'" />';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment