Created
January 20, 2013 08:43
-
-
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.
This file contains 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
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