PHP IP 지리적 위치 조회 가이드
PHP에서 IP 주소 하나의 국가, 도시 및 대략적인 좌표를 가져옵니다.
PHP에서 IP 주소 조회하기
요청은 IPv4 또는 IPv6 주소 하나를 입력받고 JSON 응답을 요청합니다. 예제 주소를 확인하려는 주소로 바꾸세요.
<?php
$ip = '8.8.8.8'; // Replace with a validated IPv4 or IPv6 address.
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new InvalidArgumentException('Invalid IP address');
}
$url = 'https://api.ipquery.io/' . rawurlencode($ip) . '?format=json';
$handle = curl_init($url);
curl_setopt_array($handle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 8,
]);
$body = curl_exec($handle);
$status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($body === false) {
$error = curl_error($handle);
throw new RuntimeException('IP lookup failed: ' . $error);
}
if ($status !== 200) {
throw new RuntimeException('IPQuery returned HTTP ' . $status);
}
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if (($data['ip'] ?? null) !== $ip || !isset($data['location']) || !is_array($data['location'])) {
throw new RuntimeException('Unexpected IPQuery response');
}
$location = $data['location'];
$countryCode = strtoupper(trim((string) ($location['country_code'] ?? '')));
$city = trim((string) ($location['city'] ?? ''));
echo 'Country code: ' . ($countryCode ?: 'Unknown') . PHP_EOL;
echo 'City: ' . ($city ?: 'Unknown') . PHP_EOL;
// Coordinates describe an approximate network location, not the user.
$latitude = $location['latitude'] ?? null;
$longitude = $location['longitude'] ?? null;
if (preg_match('/^[A-Z]{2}$/', $countryCode) &&
!in_array($countryCode, ['XX', 'ZZ'], true) &&
is_numeric($latitude) && is_numeric($longitude)) {
printf('Approximate coordinates: %.5f, %.5f%s', $latitude, $longitude, PHP_EOL);
}cURL 확장이 활성화된 PHP가 필요합니다. 연결 시간 제한은 3초이며 전체 요청 시간 제한은 8초입니다.
위치 필드 읽기
location.country_code는 두 글자 국가 코드이고 location.country는 국가 이름입니다. 국가를 알고 있어도 location.city는 비어 있을 수 있습니다. 빈 값은 알 수 없음으로 유지하세요.
location.latitude와 location.longitude는 네트워크 위치의 대략적인 좌표입니다. 표시하기 전에 사용할 수 있는 위치 이름이 있는지 확인하세요. 숫자 좌표만으로 위치가 확정되지는 않습니다. 이 좌표는 기기나 개인을 식별하지 않습니다.
요청을 보낸 연결의 주소를 확인하려면 다음을 호출하세요: https://api.ipquery.io/?format=json. 서버에서 보낸 요청은 서버가 연결에 사용하는 IP를 반환하고, 브라우저에서 보낸 요청은 해당 연결의 외부에 보이는 주소를 반환합니다.
정확성과 보안
IP 지리적 위치는 네트워크 위치의 추정값이며 기기의 위치가 아닙니다. VPN, 프록시, 모바일 네트워크 및 통신사 게이트웨이로 인해 주소가 사용자에게서 멀리 떨어진 곳으로 추정될 수 있습니다. 누락된 값을 추측으로 채우지 말고 알 수 없음으로 처리하세요.
애플리케이션이 X-Forwarded-For를 읽는 경우, 직접 제어하는 프록시가 제공한 값만 신뢰하세요. 클라이언트가 제공한 헤더는 위조될 수 있습니다. 조회 요청 전에 주소를 검증하고, 시간 제한 초과와 HTTP 오류는 성공 결과와 별도로 처리하세요.
API 참조