Skip to content

Instantly share code, notes, and snippets.

@FabianBeiner
Created January 11, 2011 10:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FabianBeiner/774257 to your computer and use it in GitHub Desktop.
Save FabianBeiner/774257 to your computer and use it in GitHub Desktop.
A Google URL Shortener Class using the new API
<?php
// Examples!
require_once 'GoogleURLShortener.php';
// Shorten an URL.
$strLongUrl = 'http://www.github.com';
if ($strShortUrl = GoogleURLShortener::shorten($strLongUrl)) {
echo $strLongUrl . ' shortened: ' . $strShortUrl . '<br>';
}
// Expand an URL.
$strShortUrl = 'http://goo.gl/ddom'; // www.linux.com
if ($strLongUrl = GoogleURLShortener::expand($strShortUrl)) {
echo $strShortUrl . ' expanded: ' . $strLongUrl . '<br>';
}
?>
<?php
class GoogleURLShortener {
public static function shorten($strUrl) {
// Would love to use FILTER_VALIDATE_URL here, but it sucks even more
// than this regular expression does.
if (!preg_match('/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $strUrl)) return false;
$oCurl = curl_init('https://www.googleapis.com/urlshortener/v1/url');
curl_setopt_array($oCurl, array (CURLOPT_HTTPHEADER => array('Content-Type: application/json')
,CURLOPT_FRESH_CONNECT => TRUE
,CURLOPT_RETURNTRANSFER => TRUE
,CURLOPT_TIMEOUT => 10
,CURLOPT_CONNECTTIMEOUT => 0
,CURLOPT_POST => TRUE
,CURLOPT_POSTFIELDS => '{"longUrl": "' . $strUrl . '"}'));
$strReturn = json_decode(curl_exec($oCurl), true);
return ($strReturn['id'] ? $strReturn['id'] : false);
}
public static function expand($strUrl) {
if (!preg_match('#http://goo.gl/(.*)#i', $strUrl)) return false;
$oCurl = curl_init('https://www.googleapis.com/urlshortener/v1/url?shortUrl=' . $strUrl);
curl_setopt_array($oCurl, array (CURLOPT_FRESH_CONNECT => TRUE
,CURLOPT_RETURNTRANSFER => TRUE
,CURLOPT_TIMEOUT => 10
,CURLOPT_CONNECTTIMEOUT => 0));
$strReturn = json_decode(curl_exec($oCurl), true);
return ($strReturn['longUrl'] ? $strReturn['longUrl'] : false);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment