-
[PHP] 단축URL(Bitly.com) API 코드 만들기[프로그램] 2023. 3. 5. 12:37728x90

긴 URL을 단축시켜주는
무료사이트가 많은데요
그 중 Bitly.com 라는 사이트를 통해
간단하게 긴 URL을 짧게 단축할 수 있습니다.
직접 사이트에서
간편하게 단축할 수 있는 방법이 있고
(아래의 포스팅을 참고해주세요 ㅎㅎㅎ)
긴 URL을 무료로 단축URL 만들기
친구들과 인터넷 사이트를 공유할 때 긴 URL 주소를 무료로 짧게 변환해주는 사이트가 있어 알려드리려고해요!! 긴 URL을 짧게 줄여주는 무료 사이트가 많이 있는데 그 중 Bitly 사이트 사용법을 소
kongmks.tistory.com
Bilty에서 제공하는 API를 이용해
프로그램에서 단축URL로 변환할 수 있는 방법이 있습니다.
오늘은 PHP 프로그램으로
Bitly API를 통해
단축URL을 만드는 방법을 알려드리도록 하겠습니다.
Bitly API 통신을 위해선
Access Token이 필요한데
URL Shortener - Short URLs & Custom Free Link Shortener | Bitly
Bitly’s Connections Platform is more than a free URL shortener, with robust link management software, advanced QR Code features, and a Link-in-bio solution.
bitly.com
bitly 사이트에 로그인을 한 후
아래의 메뉴로 이동해
Access Token 값을 받아야 합니다!

그럼 준비는 다 끝났습니다
아래의 "shortenURLForBitly" 함수를 복사해서
"{TOKEN 값}"에
방금 사이트에서 획득한
Access token 값을 입력하면 됩니다!
<?php function shortenURLForBitly($url) { $access_token = "{TOKEN 값}"; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,"https://api-ssl.bitly.com/v4/shorten"); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array( "long_url" => $url ))); curl_setopt($ch,CURLOPT_HTTPHEADER,array( "Content-Type: application/json", "Authorization: Bearer ".$access_token )); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); // Execute the post $result = curl_exec($ch); // Close the connection curl_close($ch); // Return the result return json_decode($result,true); } print_r(shortenURLForBitly("https://www.daum.net")); ?>단축할 주소를
매개변수로 보내주면
아래와 같은 결과값을 받을 수 있습니다!

이 정보를 아래와 같이
여러분들이 원하는 입맛에 맞게
값을 추출해
프로그램을 만들면 된답니다!
<? function shortenURLForBitly($url) { $access_token = "{TOKEN 값}"; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,"https://api-ssl.bitly.com/v4/shorten"); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array( "long_url" => $url ))); curl_setopt($ch,CURLOPT_HTTPHEADER,array( "Content-Type: application/json", "Authorization: Bearer ".$access_token )); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); // Execute the post $result = curl_exec($ch); // Close the connection curl_close($ch); // Return the result return json_decode($result,true); } $shorturl = shortenURLForBitly("https://www.daum.net"); echo $shorturl['id']; // bit.ly/3YhchBa 출력 echo "<br>"; echo $shorturl['link']; // https://bit.ly/3YhchBa 출력 ?>그럼 bitly API 통신하는 PHP 코드 만드는 방법에 대한 포스팅을
마치도록 하겠습니다!
728x90