Shorten URLs using Bit.ly API (PHP)
Here's PHP function that comes in handy when you want to shorten long URLs into short Bit.ly URLs, before sharing it to Twitter or other Social networks. First you need to create Bit.ly OAuth application here, when you create an application you will be able to generate "Generic Access Token" under this application to make API requests on behalf of your own account. Once you are ready, you can drop this function into your project to convert your long URLs to bit.ly short URLs.PHP
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
function bitly_url_shorten($long_url, $access_token, $domain)
{
$url = 'https://api-ssl.bitly.com/v3/shorten?access_token='.$access_token.'&longUrl='.urlencode($long_url).'&domain='.$domain;
try {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$output = json_decode(curl_exec($ch));
} catch (Exception $e) {
}
if(isset($output)){return $output->data->url;}
}
Usage
PHP
- 1
- 2
//bitly_url_shorten(Long URL, Access Token, Bitly Short Domain);
echo bitly_url_shorten($share_url, 'woeuroeurow2394732947ewdslkfjweiusdfsj', 'j.mp');