본문 바로가기

프로그래밍/PHP

PHP에서 bit.ly 이용하여 단축 URL 만들기

1. bit.ly 회원가입하기 - 링크
 - bit.ly 를 이용한 단축 URL 을 이용하려면 우선 bit.ly 에 회원가입을 해야합니다.


2. apiKey 확인하기
https://bitly.com/a/settings/advanced 페이지의 하단에 보면 아래 그림과 같이 Login 과 API Key 값을 확인할수 있습니다.


3. 함수
- $login, $apiKey 값에 위에서 확인한 값을 대입한다.

function bitly($uri=false) {

$login = 'o_xxxxxxxxxx';

$apiKey = 'R_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';


if (stripos($uri, 'http://') === false && stripos($uri, 'https://') === false) $uri = 'http://'.$uri;


$url = "https://api-ssl.bitly.com/v3/shorten?login={$login}&apiKey={$apiKey}&format=txt&uri=".$uri;


// file_get_contents()를 사용할수 있다면

if (ini_get('allow_url_fopen')) {

$shortURL = file_get_contents($url);

} else {

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HEADER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$shortURL = curl_exec($ch);

curl_close($ch);

unset($ch);

}


return trim($shortURL);

}