Generate Bit.ly Short URLs Using PHP – API Version 3
We have share how to create Bit.ly short URLs using PHP.Bit.ly is a powerful API to generate short URL. To use this API you have to signup for an API key.The API also provides methods to get the long URL from a short one, validate a short one, and also get all sorts of statistics about a URL that you’ve shortened using bit.ly.
Step 1 Create Account
If you do not have a Bit.ly account Click here!.
Step 2 Create an OAuth application
Next step create your API keys. Click here!
Then click “Get Registration Code” Button
Step 3 Create Your App
You will receive an email with the authentication link. Click the link, and fill your information. then click “Create Your App” Button.
Step 3 Client ID and Client Secret
Your Client ID and Client Secret. You will need to generate an Access Token.
Step 4 Using bit.ly with PHP
Here’s how you can create short URLs and expand short URLs using Bit.ly.
I-Returns Short URL
1 2 3 4 5 6 7 |
<?php //Returns Short URL function getBitlyShortURL($url,$login,$appkey,$format='') { $connectURL = 'http://api.bit.ly/v3/shorten?login='.$login.'&apiKey='.$appkey.'&uri='.urlencode($url).'&format='.$format; return getCURLResult($connectURL); } ?> |
II-Returns Expanded URL
1 2 3 4 5 6 7 |
<?php //Returns Expanded URL function getBitlyLongURL($url,$login,$appkey,$format='') { $connectURL = 'http://api.bit.ly/v3/expand?login='.$login.'&apiKey='.$appkey.'&shortUrl='.urlencode($url).'&format='.$format; return getCURLResult($connectURL); } ?> |
III- Returns result form URL
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php //Returns result form URL function getCURLResult($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } ?> |
IV- Final result
1 2 3 4 5 6 7 |
<?php //Get Short URL $shortURL = getBitlyShortURL('https://webhaunt.com','xxxxxxxxxx','xxxxxxxxxx'); //Get long URL from the short one $long_url = getBitlyLongURL($shortURL,'xxxxxxxxxx','xxxxxxxxxx'); ?> |