Created
June 16, 2012 16:54
-
-
Save MikeRogers0/2941923 to your computer and use it in GitHub Desktop.
Shorten URLs using the Google URL Shortener and PHP
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 | |
// 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