Created
January 11, 2011 10:03
-
-
Save FabianBeiner/774257 to your computer and use it in GitHub Desktop.
A Google URL Shortener Class using the new API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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>'; | |
} | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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