เขียน php ย่อ URL กับ bit.ly | Create Bit.ly Short URLs Using PHP: API Version 3
หน้าแรก PHP MySQL เกร็ดความรู้ เขียน php ย่อ URL กับ bit.ly | Create Bit.ly Short URLs Using PHP: API Version 3
Bit.ly is a great URL shortening service. I love their reliability, shortness of the URL, and the information they provide about a given URL. Recently Bit.ly updated their API to version 3 so I thought I'd update my original Bit.ly post. Here's how you can create short URLs and expand short URLs using Bit.ly.
The PHP
/* returns the shortened url */
function get_bitly_short_url($url,$login,$appkey,$format='txt') {
$connectURL = 'http://api.bit.ly/v3/shorten?login='.$login.'&apiKey='.$appkey.'&uri='.urlencode($url).'&format='.$format;
return curl_get_result($connectURL);
}
/* returns expanded url */
function get_bitly_long_url($url,$login,$appkey,$format='txt') {
$connectURL = 'http://api.bit.ly/v3/expand?login='.$login.'&apiKey='.$appkey.'&shortUrl='.urlencode($url).'&format='.$format;
return curl_get_result($connectURL);
}
/* returns a result form url */
function curl_get_result($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;
}
/* get the short url */
$short_url = get_bitly_short_url('http://davidwalsh.name/','davidwalshblog','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
/* get the long url from the short one */
$long_url = get_bitly_long_url($short_url,'davidwalshblog','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
All you really need to is pass your appkey and login (you must sign up for their API service), the long or short URL, and the format which you'd like the result to be returned in. If you just want a simple URL with no other information, use the default "txt" format. Retrieving the XML or JSON formats will provide you more information about the URL.
Bit.ly is awesome. I mean, Twitter uses them -- what more of an endorsement would you need.
ขึ้นไปด้านบน
