Geoip2
인증된 제출자geoip2/geoip2
MaxMind GeoIP PHP API
GeoIP PHP API 사용 안내
소개
이 패키지는 GeoIP와 GeoLite의 웹 서비스 및 데이터베이스에 접근할 수 있는 API를 제공합니다.
Composer로 설치하기
이 패키지는 Composer로 설치하는 것을 권장합니다.
Composer 다운로드
프로젝트 루트 디렉터리에서 다음 명령을 실행하세요.
curl -sS https://getcomposer.org/installer | php실행 후 프로젝트 디렉터리에 composer.phar 파일이 생성됩니다.
의존성 설치
프로젝트 루트에서 다음 명령을 실행하세요.
php composer.phar require geoip2/geoip2:^3.4.0프로젝트 디렉터리에 composer.json, composer.lock 파일과 vendor 디렉터리가 생성됩니다. 버전 관리 시스템을 사용한다면 composer.json을 버전 관리에 포함하세요.
오토로더 불러오기
의존성을 설치한 뒤 코드에서 Composer 오토로더를 불러와야 합니다.
require 'vendor/autoload.php';Phar로 설치하기
Composer 사용을 강력히 권장하지만, GeoIP 의존성 대부분을 포함한 phar 아카이브도 제공합니다. 최신 phar 아카이브는 릴리스 페이지에서 받을 수 있습니다.
의존성 설치
phar 아카이브를 사용하려면 PHP Phar 확장을 설치하고 활성화해야 합니다.
이 아카이브로 웹 서비스 요청을 보내려면 PHP cURL 확장도 설치해야 합니다. Debian 계열 배포판에서는 일반적으로 php-curl 패키지로 설치할 수 있습니다. 다른 운영체제는 해당 문서를 확인하세요. 확장을 설치한 뒤 웹 서버를 다시 시작해야 할 수도 있습니다.
cURL 확장이 없으면 다음과 같은 오류가 발생할 수 있습니다.
PHP Fatal error: Uncaught Error: Call to undefined function MaxMind\WebService\curl_version()
패키지 불러오기
스크립트에서 아카이브를 불러오면 사용할 수 있습니다.
require 'geoip2.phar';선택 사항: C 확장
MaxMind DB API는 GeoIP 또는 GeoLite 데이터베이스의 조회 성능을 크게 높일 수 있는 선택적 C 확장을 제공합니다. 설치 방법은 해당 API에 포함된 안내를 따르세요.
이 확장은 웹 서비스 조회에는 영향을 주지 않습니다.
IP 위치 정보 사용 시 주의 사항
IP 위치 정보는 본질적으로 정확하지 않습니다. 표시되는 위치가 인구 분포의 중심 부근인 경우도 많습니다. GeoIP 데이터베이스나 웹 서비스에서 얻은 위치 정보를 특정 주소나 가구를 식별하는 데 사용해서는 안 됩니다.
데이터베이스 리더
사용 방법
먼저 \GeoIp2\Database\Reader 객체를 만들고 생성자의 첫 번째 인수로 데이터베이스 파일 경로를 전달하세요. 그런 다음 사용하는 데이터베이스에 해당하는 메서드를 호출합니다.
조회에 성공하면 데이터베이스 레코드를 나타내는 모델 클래스가 반환됩니다. 이 모델에는 IP 주소가 위치한 도시 등 데이터의 각 부분을 담는 여러 컨테이너 클래스가 포함됩니다.
레코드를 찾지 못하면 \GeoIp2\Exception\AddressNotFoundException이 발생합니다. 데이터베이스가 유효하지 않거나 손상되었다면 \MaxMind\Db\InvalidDatabaseException이 발생합니다.
자세한 내용은 API 문서를 확인하세요.
도시 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$cityDbReader = new Reader('/usr/local/share/GeoIP/GeoIP2-City.mmdb');
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $cityDbReader->city('128.101.101.101');
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '美国'
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323
print($record->traits->network . "\n"); // '128.101.101.101/32'
Anonymous IP 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$anonymousDbReader = new Reader('/usr/local/share/GeoIP/GeoIP2-Anonymous-IP.mmdb');
$record = $anonymousDbReader->anonymousIp('128.101.101.101');
if ($record->isAnonymous) { print "anon\n"; }
print($record->ipAddress . "\n"); // '128.101.101.101'
print($record->network . "\n"); // '128.101.101.101/32'
Anonymous Plus 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$anonymousDbReader = new Reader('/usr/local/share/GeoIP/GeoIP-Anonymous-Plus.mmdb');
$record = $anonymousDbReader->anonymousPlus('203.0.113.0');
print($record->anonymizerConfidence . "\n"); // 30
print($record->networkLastSeen . "\n"); // '2025-04-14'
print($record->providerName . "\n"); // 'FooBar VPN'
print($record->ipAddress . "\n"); // '203.0.113.0'
print($record->network . "\n"); // '203.0.113.0/32'
연결 유형 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$connectionTypeDbReader = new Reader('/usr/local/share/GeoIP/GeoIP2-Connection-Type.mmdb');
$record = $connectionTypeDbReader->connectionType('128.101.101.101');
print($record->connectionType . "\n"); // 'Corporate'
print($record->ipAddress . "\n"); // '128.101.101.101'
print($record->network . "\n"); // '128.101.101.101/32'
도메인 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$domainDbReader = new Reader('/usr/local/share/GeoIP/GeoIP2-Domain.mmdb');
$record = $domainDbReader->domain('128.101.101.101');
print($record->domain . "\n"); // 'umn.edu'
print($record->ipAddress . "\n"); // '128.101.101.101'
print($record->network . "\n"); // '128.101.101.101/32'
Enterprise 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$enterpriseDbReader = new Reader('/usr/local/share/GeoIP/GeoIP2-Enterprise.mmdb');
// Use the ->enterprise method to do a lookup in the Enterprise database
$record = $enterpriseDbReader->enterprise('128.101.101.101');
print($record->country->confidence . "\n"); // 99
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '美国'
print($record->mostSpecificSubdivision->confidence . "\n"); // 77
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->confidence . "\n"); // 60
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->accuracyRadius . "\n"); // 50
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323
print($record->traits->network . "\n"); // '128.101.101.101/32'
ISP 조회 예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$ispDbReader = new Reader('/usr/local/share/GeoIP/GeoIP2-ISP.mmdb');
$record = $ispDbReader->isp('128.101.101.101');
print($record->autonomousSystemNumber . "\n"); // 217
print($record->autonomousSystemOrganization . "\n"); // 'University of Minnesota'
print($record->isp . "\n"); // 'University of Minnesota'
print($record->organization . "\n"); // 'University of Minnesota'
print($record->ipAddress . "\n"); // '128.101.101.101'
print($record->network . "\n"); // '128.101.101.101/32'
데이터베이스 업데이트
GeoIP Update 프로그램으로 데이터베이스를 최신 상태로 유지할 수 있습니다. 자세한 내용은 개발자 포털의 GeoIP Update 안내를 확인하세요.
웹 서비스 클라이언트
사용 방법
\GeoIp2\WebService\Client 객체를 만들고 자신의 $accountId와 $licenseKey를 전달하세요.
$client = new Client(42, 'abcdef123456');생성자에 추가 인수를 전달할 수도 있습니다. 세 번째 인수는 클라이언트가 생성한 모델 클래스의 ->name을 사용할 때 적용할 언어 우선순위를 지정합니다. 네 번째 인수에는 host, timeout 등의 추가 옵션을 지정합니다.
예를 들어 GeoIP 대신 GeoLite 웹 서비스를 호출하려면 다음과 같이 설정하세요.
$client = new Client(42, 'abcdef123456', ['en'], ['host' => 'geolite.info']);운영용 GeoIP 웹 서비스 대신 Sandbox GeoIP 웹 서비스를 호출하려면 다음과 같이 설정하세요.
$client = new Client(42, 'abcdef123456', ['en'], ['host' => 'sandbox.maxmind.com']);클라이언트를 만든 뒤 조회할 IP 주소를 전달하여 원하는 엔드포인트에 해당하는 메서드를 호출합니다.
$record = $client->city('128.101.101.101');요청이 성공하면 호출한 엔드포인트에 해당하는 모델 클래스가 반환됩니다. 이 모델에는 웹 서비스가 반환한 데이터의 각 부분을 나타내는 여러 레코드 클래스가 들어 있습니다.
오류가 발생하면 구조화된 예외가 발생합니다.
자세한 내용은 API 문서를 확인하세요.
예제
<?php
require_once 'vendor/autoload.php';
use GeoIp2\WebService\Client;
// This creates a Client object that can be reused across requests.
// Replace "42" with your account ID and "license_key" with your license
// key. Set the "host" to "geolite.info" in the fourth argument options
// array to use the GeoLite web service instead of the GeoIP web
// service. Set the "host" to "sandbox.maxmind.com" in the fourth argument
// options array to use the Sandbox GeoIP web service instead of the
// production GeoIP web service.
$client = new Client(42, 'abcdef123456');
// Replace "city" with the method corresponding to the web service that
// you are using, e.g., "country", "insights".
$record = $client->city('128.101.101.101');
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '美国'
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323
print($record->traits->network . "\n"); // '128.101.101.101/32'
데이터베이스나 배열의 키로 사용할 값
names 속성의 값을 데이터베이스나 배열의 키로 사용하는 것은 강력히 권장하지 않습니다.
이름은 릴리스 사이에 바뀔 수 있습니다. 대신 다음 값 중 하나를 사용하는 것을 권장합니다.
GeoIp2\Record\City-$city->geonameIdGeoIp2\Record\Continent-$continent->code또는$continent->geonameIdGeoIp2\Record\Country및GeoIp2\Record\RepresentedCountry-$country->isoCode또는$country->geonameIdGeoIp2\Record\Subdivision-$subdivision->isoCode또는$subdivision->geonameId
반환되는 데이터
여러 엔드포인트가 같은 기본 레코드를 반환하더라도, 값이 채워질 수 있는 속성은 엔드포인트마다 다릅니다. 또한 어떤 엔드포인트가 특정 데이터를 제공하더라도 MaxMind가 모든 IP 주소에 대해 그 데이터를 갖고 있는 것은 아닙니다.
따라서 어느 엔드포인트에서든 일부 또는 모든 속성이 비어 있는 레코드가 반환될 수 있습니다.
엔드포인트별로 반환할 수 있는 데이터는 GeoIP 웹 서비스 문서를 확인하세요.
항상 반환되는 유일한 데이터는 GeoIp2\Record\Traits 레코드의 ipAddress 속성입니다.
GeoNames 연동
GeoNames는 거주 지역을 포함한 전 세계 지리 정보에 대한 웹 서비스와 다운로드 가능한 데이터베이스를 제공합니다. 무료 데이터와 유료 프리미엄 데이터를 모두 제공하며, 각 지리 항목은 정수형 geonameId로 고유하게 식별됩니다.
GeoIP 웹 서비스와 데이터베이스가 반환하는 많은 레코드에는 geonameId 속성이 있습니다. 이 값은 GeoNames 데이터베이스에 있는 도시·지역·국가 등의 지리 항목 ID입니다.
MaxMind가 제공하는 데이터 중 일부도 GeoNames에서 가져옵니다. 지명, ISO 코드 및 이와 유사한 데이터는 GeoNames 프리미엄 데이터 세트를 사용합니다.
데이터 오류 신고
IP 주소가 잘못된 위치에 연결된 경우에는 MaxMind에 수정 요청을 제출하세요.
철자 오류처럼 다른 종류의 문제라면 먼저 GeoNames 사이트를 확인하세요. 장소를 검색한 뒤 지도에서 해당 장소를 찾으면 move, edit, alternate names 등 데이터를 수정할 수 있는 링크가 표시됩니다. 수정 사항이 GeoNames 데이터 세트에 반영되면 이후 MaxMind 릴리스에도 자동으로 포함됩니다.
MaxMind 유료 고객이면서 수정 요청을 어디에 제출해야 할지 모르겠다면 MaxMind 지원팀에 문의하세요.
기타 지원
이 코드와 관련된 문제는 GitHub 이슈 트래커에 신고하세요.
클라이언트 API에 국한되지 않는 MaxMind 서비스 문제라면 지원 페이지를 확인하세요.
요구 사항
이 라이브러리는 PHP 8.1 이상이 필요합니다.
또한 MaxMind DB Reader에 의존합니다.
기여하기
패치와 풀 리퀘스트를 환영합니다. 모든 코드는 PSR-12 스타일 지침을 따라야 합니다. 가능하면 단위 테스트도 포함해 주세요.
maxmind-db 폴더의 테스트 데이터는 git submodule update --init --recursive를 실행하거나, 처음 복제할 때 --recursive를 추가하거나, https://github.com/maxmind/MaxMind-DB 에서 받을 수 있습니다.
버전 관리
GeoIP PHP API는 유의적 버전 관리를 사용합니다.
저작권 및 라이선스
이 소프트웨어의 저작권은 MaxMind, Inc.에 있습니다. Copyright (c) 2013-2026.
이 소프트웨어는 Apache License, Version 2.0으로 배포되는 자유 소프트웨어입니다.