IP를 기반으로 국가 정보 무료 API > 정보공유

본문 바로가기

정보공유

일반글
API

IP를 기반으로 국가 정보 무료 API

페이지 정보

게시물QR코드

본문

/**

 * ip2c.org API를 이용해 IP 주소로 국가 정보를 조회합니다.

 *

 * @param string $ip 조회할 IP 주소

 * @return array 결과 배열 (성공 시 country_code2, country_code3, country_name 포함 / 실패 시 status = 0)

 */

function ip2c_get_country_info($ip) {

    $url = "https://ip2c.org/{$ip}";


    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // 타임아웃 설정

    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // SSL 인증 무시


    $response = curl_exec($ch);

    curl_close($ch);


    if (!$response) {

        return [

            'status' => 0,

            'country_code2' => '',

            'country_code3' => '',

            'country_name' => '',

            'raw' => ''

        ];

    }


    $parts = explode(';', trim($response));

    return [

        'status' => (int)($parts[0] ?? 0),

        'country_code2' => $parts[1] ?? '',

        'country_code3' => $parts[2] ?? '',

        'country_name' => $parts[3] ?? '',

        'raw' => $response

    ];

}


$ip = $_SERVER['REMOTE_ADDR']; // 또는 테스트용: '8.8.8.8'

$info = ip2c_get_country_info($ip);

print_r2($info);

if ($info['status'] === 1) {

    echo "국가: {$info['country_name']} ({$info['country_code2']})";

} else {

    echo "국가 정보 조회 실패";

}

댓글목록

등록된 댓글이 없습니다.

  • Addr.부산광역시 부산진구 중앙대로 666번길 50, 더샵센트럴스타 CEO. 이경애 Email. gnuwiz@naver.com
  • BR. 625-68-00172 TRC. 2024-부산진-0560 TEL. 0507-1382-2790
Copyright © 2017 ~ 그누위즈. All rights reserved.