[PHP] 짧은 주소로 바꾸기 (bit.ly / j.mp / is.gd / v.gd / to.ly / goo.gl / durl.me / tinyurl.com)

  텍스트큐브의 SNS에 글 보내기 확장기능에서 쪽글에 글 주소를 넣으려고 써먹은 PHP 함수이다, 다른 곳에 올라온 예제를 참고하여 switch-case로 여러 짧은 주소(bit.ly / j.mp / is.gd / v.gd / to.ly / goo.gl / durl.me / tinyurl.com)를 넣을 수 있게 하였다.

  goo.gl과 durl.me는 짧은 주소를 JSON 형식으로 받고, 나머지는 글월(텍스트) 형식으로 받는다. get_shorURL("긴 주소", "짧은 주소 종류");라고 넣으면 짧은 주소를 돌려준다. bit.ly / j.mp와 goo.gl은 계정을 만들어서 API 열쇠(key)를 받아 넣어야 쓸 수 있다.



function get_shortURL($longURL, $shortURL_domain) {
switch($shortURL_domain) {
case "bit.ly" :
case "j.mp" :
$login = "bit.ly/j.mp 계정 아이디";
$api_key = "API 열쇠";
$curlopt_url = "http://api.".$shortURL_domain."/v3/shorten?login=".$login."&apiKey=".$api_key."&uri=".$longURL."&format=txt";
break;
case "is.gd" :
$curlopt_url = "http://is.gd/api.php?longurl=".$longURL;
break;
case "v.gd" :
$curlopt_url = "http://v.gd/create.php?format=simple&url=".$longURL;
break;
case "to.ly" :
$curlopt_url = "http://to.ly/api.php?longurl=".$longURL;
break;
case "goo.gl" :
$api_key = "API 열쇠";
$curlopt_url = "https://www.googleapis.com/urlshortener/v1/url?key=".$api_key;
break;
case "durl.me" :
$curlopt_url = "http://durl.me/api/Create.do?type=json&longurl=".$longURL;
break;
case "tinyurl" :
$curlopt_url = "http://tinyurl.com/api-create.php?url=".$longURL;
break;

} $ch = curl_init();
//$timeout = 10;

curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
if($shortURL_domain == "goo.gl" || $shortURL_domain == "durl.me") {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$jsonArray = array('longUrl' => $longURL);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonArray));
$shortURL = curl_exec($ch);
curl_close($ch);
$result_array = json_decode($shortURL, true);

if($result_array['shortUrl']) return $result_array['shortUrl']; // durl.me
else if($result_array['id']) return $result_array['id']; // goo.gl
else return false;
}
$shortURL = curl_exec($ch);
curl_close($ch);

// bit.ly(j.mp) 주소 끝에 붙은 줄바꿈 문자를 없앰
if( ($shortURL_domain == "j.mp" || $shortURL_domain == "bit.ly") && bin2hex(substr($shortURL, -1, 1)) == "0a") $shortURL = substr($shortURL, 0, strlen($shortURL)-1);

return $shortURL;
}
글 걸기 주소 : 이 글에는 글을 걸 수 없습니다.

덧글을 달아 주세요

  1. (V,.L;) 2013/04/05 10:49 고유주소 고치기 답하기

    감사합니다.