Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

PHP API for GeoIP2 webservice client and database reader

License

NotificationsYou must be signed in to change notification settings

maxmind/GeoIP2-php

Repository files navigation

Description

This package provides an API for the GeoIP2 and GeoLite2web services anddatabases.

Install via Composer

We recommend installing this package withComposer.

Download Composer

To download Composer, run in the root directory of your project:

curl -sS https://getcomposer.org/installer| php

You should now have the filecomposer.phar in your project directory.

Install Dependencies

Run in your project root:

php composer.phar require geoip2/geoip2:^3.2.0

You should now have the filescomposer.json andcomposer.lock as well asthe directoryvendor in your project directory. If you use a version controlsystem,composer.json should be added to it.

Require Autoloader

After installing the dependencies, you need to require the Composer autoloaderfrom your code:

require'vendor/autoload.php';

Install via Phar

Although we strongly recommend using Composer, we also provide aphar archive containing most of thedependencies for GeoIP2. Our latest phar archive is available onour releases page.

Install Dependencies

In order to use the phar archive, you must have the PHPPhar extension installed andenabled.

If you will be making web service requests, you must have the PHPcURL extensioninstalled to use this archive. For Debian based distributions, this cantypically be found in the thephp-curl package. For other operatingsystems, please consult the relevant documentation. After installing theextension you may need to restart your web server.

If you are missing this extension, you will see errors like the following:

PHP Fatal error:  Uncaught Error: Call to undefined function MaxMind\WebService\curl_version()

Require Package

To use the archive, just require it from your script:

require'geoip2.phar';

Optional C Extension

TheMaxMind DB APIincludes an optional C extension that you may install to dramatically increasethe performance of lookups in GeoIP2 or GeoLite2 databases. To install, pleasefollow the instructions included with that API.

The extension has no effect on web-service lookups.

IP Geolocation Usage

IP geolocation is inherently imprecise. Locations are often near the center ofthe population. Any location provided by a GeoIP2 database or web serviceshould not be used to identify a particular address or household.

Database Reader

Usage

To use this API, you must create a new\GeoIp2\Database\Reader object withthe path to the database file as the first argument to the constructor. Youmay then call the method corresponding to the database you are using.

If the lookup succeeds, the method call will return a model class for therecord in the database. This model in turn contains multiple containerclasses for the different parts of the data such as the city in which theIP address is located.

If the record is not found, a\GeoIp2\Exception\AddressNotFoundExceptionis thrown. If the database is invalid or corrupt, a\MaxMind\Db\InvalidDatabaseException will be thrown.

See theAPI documentation for moredetails.

City Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$cityDbReader =newReader('/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.9733print($record->location->longitude ."\n");// -93.2323print($record->traits->network ."\n");// '128.101.101.101/32'

Anonymous IP Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$anonymousDbReader =newReader('/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 Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$anonymousDbReader =newReader('/usr/local/share/GeoIP/GeoIP-Anonymous-Plus.mmdb');$record =$anonymousDbReader->anonymousIp('203.0.113.0');print($record->anonymizerConfidence ."\n");// 30print($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'

Connection-Type Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$connectionTypeDbReader =newReader('/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'

Domain Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$domainDbReader =newReader('/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 Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$enterpriseDbReader =newReader('/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");// 99print($record->country->isoCode ."\n");// 'US'print($record->country->name ."\n");// 'United States'print($record->country->names['zh-CN'] ."\n");// '美国'print($record->mostSpecificSubdivision->confidence ."\n");// 77print($record->mostSpecificSubdivision->name ."\n");// 'Minnesota'print($record->mostSpecificSubdivision->isoCode ."\n");// 'MN'print($record->city->confidence ."\n");// 60print($record->city->name ."\n");// 'Minneapolis'print($record->postal->code ."\n");// '55455'print($record->location->accuracyRadius ."\n");// 50print($record->location->latitude ."\n");// 44.9733print($record->location->longitude ."\n");// -93.2323print($record->traits->network ."\n");// '128.101.101.101/32'

ISP Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\Database\Reader;// This creates the Reader object, which should be reused across// lookups.$ispDbReader =newReader('/usr/local/share/GeoIP/GeoIP2-ISP.mmdb');$record =$ispDbReader->isp('128.101.101.101');print($record->autonomousSystemNumber ."\n");// 217print($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'

Database Updates

You can keep your databases up to date with ourGeoIP Update program.Learn more about GeoIP Update on our developerportal.

Web Service Client

Usage

To use this API, you must create a new\GeoIp2\WebService\Clientobject with your$accountId and$licenseKey:

$client =newClient(42,'abcdef123456');

You may also call the constructor with additional arguments. The third argumentspecifies the language preferences when using the->name method on the modelclasses that this client creates. The fourth argument is additional optionssuch ashost andtimeout.

For instance, to call the GeoLite2 web service instead of the GeoIP2 webservice:

$client =newClient(42,'abcdef123456', ['en'], ['host' =>'geolite.info']);

To call the Sandbox GeoIP2 web service instead of the production GeoIP2 webservice:

$client =newClient(42,'abcdef123456', ['en'], ['host' =>'sandbox.maxmind.com']);

After creating the client, you may now call the method corresponding to aspecific endpoint with the IP address to look up, e.g.:

$record =$client->city('128.101.101.101');

If the request succeeds, the method call will return a model class for theendpoint you called. This model in turn contains multiple record classes, eachof which represents part of the data returned by the web service.

If there is an error, a structured exception is thrown.

See theAPI documentation for moredetails.

Example

<?phprequire_once'vendor/autoload.php';useGeoIp2\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 GeoLite2 web service instead of the GeoIP2 web// service. Set the "host" to "sandbox.maxmind.com" in the fourth argument// options array to use the Sandbox GeoIP2 web service instead of the// production GeoIP2 web service.$client =newClient(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.9733print($record->location->longitude ."\n");// -93.2323print($record->traits->network ."\n");// '128.101.101.101/32'

Values to use for Database or Array Keys

We strongly discourage you from using a value from anynames property asa key in a database or array.

These names may change between releases. Instead we recommend using one of thefollowing:

  • GeoIp2\Record\City -$city->geonameId
  • GeoIp2\Record\Continent -$continent->code or$continent->geonameId
  • GeoIp2\Record\Country andGeoIp2\Record\RepresentedCountry -$country->isoCode or$country->geonameId
  • GeoIp2\Record\Subdivision -$subdivision->isoCode or$subdivision->geonameId

What data is returned?

While many of the end points return the same basic records, the attributeswhich can be populated vary between end points. In addition, while an endpoint may offer a particular piece of data, MaxMind does not always have everypiece of data for any given IP address.

Because of these factors, it is possible for any end point to return a recordwhere some or all of the attributes are unpopulated.

See theGeoIP2 web service docsfor details on what data each end point may return.

The only piece of data which is always returned is theipAddressattribute in theGeoIp2\Record\Traits record.

Integration with GeoNames

GeoNames offers web services and downloadabledatabases with data on geographical features around the world, includingpopulated places. They offer both free and paid premium data. Eachfeature is unique identified by ageonameId, which is an integer.

Many of the records returned by the GeoIP2 web services and databasesinclude ageonameId property. This is the ID of a geographical feature(city, region, country, etc.) in the GeoNames database.

Some of the data that MaxMind provides is also sourced from GeoNames. Wesource things like place names, ISO codes, and other similar data fromthe GeoNames premium data set.

Reporting data problems

If the problem you find is that an IP address is incorrectly mapped,pleasesubmit your correction to MaxMind.

If you find some other sort of mistake, like an incorrect spelling,please check theGeoNames site first. Onceyou've searched for a place and found it on the GeoNames map view, thereare a number of links you can use to correct data ("move", "edit","alternate names", etc.). Once the correction is part of the GeoNamesdata set, it will be automatically incorporated into future MaxMindreleases.

If you are a paying MaxMind customer and you're not sure where to submita correction, pleasecontact MaxMind support for help.

Other Support

Please report all issues with this code using theGitHub issue tracker.

If you are having an issue with a MaxMind service that is not specificto the client API, please seeour support page.

Requirements

This library requires PHP 8.1 or greater.

This library also relies on theMaxMind DB Reader.

Contributing

Patches and pull requests are encouraged. All code should follow the PSR-2style guidelines. Please include unit tests whenever possible. You may obtainthe test data for the maxmind-db folder by runninggit submodule update --init --recursive or adding--recursive to your initial clone, or fromhttps://github.com/maxmind/MaxMind-DB

Versioning

The GeoIP2 PHP API usesSemantic Versioning.

Copyright and License

This software is Copyright (c) 2013-2025 by MaxMind, Inc.

This is free software, licensed under the Apache License, Version 2.0.

About

PHP API for GeoIP2 webservice client and database reader

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors35


[8]ページ先頭

©2009-2025 Movatter.jp