Skip to content

Instantly share code, notes, and snippets.

@xhezairbey
Created October 27, 2011 23:42
Show Gist options
  • Save xhezairbey/1321215 to your computer and use it in GitHub Desktop.
Save xhezairbey/1321215 to your computer and use it in GitHub Desktop.
BitLy API v3 Shorten PHP
<?php
function bitly_shorten($url) {
$login = "bitly_login";
$apikey = "bitly_apikey";
$format = "json";
$query = array("login" => $login,
"apiKey" => $apikey,
"longUrl" => urlencode($url),
"format" => $format);
$query = http_build_query($query);
$final_url = "http://api.bitly.com/v3/shorten?".$query;
if (function_exists("file_get_contents"))
$response = file_get_contents($final_url);
else {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $final_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$response = curl_exec($ch);
curl_close($ch);
}
$response = json_decode($response);
if($response->status_code == 0 && $response->status_txt == "OK")
return $response->data->url;
else
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment