• Stars
    star
    2,279
  • Rank 19,464 (Top 0.4 %)
  • Language
    PHP
  • License
    Apache License 2.0
  • Created about 11 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP API for GeoIP2 webservice client and database reader

GeoIP2 PHP API

Description

This package provides an API for the GeoIP2 and GeoLite2 web services and databases.

Install via Composer

We recommend installing this package with Composer.

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 file composer.phar in your project directory.

Install Dependencies

Run in your project root:

php composer.phar require geoip2/geoip2:~2.0

You should now have the files composer.json and composer.lock as well as the directory vendor in your project directory. If you use a version control system, composer.json should be added to it.

Require Autoloader

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

require 'vendor/autoload.php';

Install via Phar

Although we strongly recommend using Composer, we also provide a phar archive containing most of the dependencies for GeoIP2. Our latest phar archive is available on our releases page.

Install Dependencies

In order to use the phar archive, you must have the PHP Phar extension installed and enabled.

If you will be making web service requests, you must have the PHP cURL extension installed to use this archive. For Debian based distributions, this can typically be found in the the php-curl package. For other operating systems, please consult the relevant documentation. After installing the extension 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

The MaxMind DB API includes an optional C extension that you may install to dramatically increase the performance of lookups in GeoIP2 or GeoLite2 databases. To install, please follow 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 of the population. Any location provided by a GeoIP2 database or web service should 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 with the path to the database file as the first argument to the constructor. You may then call the method corresponding to the database you are using.

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

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

See the API documentation for more details.

City Example

<?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 Example

<?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'

Connection-Type Example

<?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'

Domain Example

<?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 Example

<?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 Example

<?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'

Database Updates

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

There is also a third-party tool for updating databases using PHP and Composer. MaxMind does not offer support for this tool or maintain it. Learn more about the Geoip2 Update tool for PHP and Composer on its GitHub page.

Web Service Client

Usage

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

$client = new Client(42, 'abcdef123456');

You may also call the constructor with additional arguments. The third argument specifies the language preferences when using the ->name method on the model classes that this client creates. The fourth argument is additional options such as host and timeout.

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

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

After creating the client, you may now call the method corresponding to a specific 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 the endpoint you called. This model in turn contains multiple record classes, each of which represents part of the data returned by the web service.

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

See the API documentation for more details.

Example

<?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 GeoLite2 web service instead of the GeoIP2 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'

Values to use for Database or Array Keys

We strongly discourage you from using a value from any names property as a key in a database or array.

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

  • GeoIp2\Record\City - $city->geonameId
  • GeoIp2\Record\Continent - $continent->code or $continent->geonameId
  • GeoIp2\Record\Country and GeoIp2\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 attributes which can be populated vary between end points. In addition, while an end point may offer a particular piece of data, MaxMind does not always have every piece of data for any given IP address.

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

See the GeoIP2 web service docs for details on what data each end point may return.

The only piece of data which is always returned is the ipAddress attribute in the GeoIp2\Record\Traits record.

Integration with GeoNames

GeoNames offers web services and downloadable databases with data on geographical features around the world, including populated places. They offer both free and paid premium data. Each feature is unique identified by a geonameId, which is an integer.

Many of the records returned by the GeoIP2 web services and databases include a geonameId 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. We source things like place names, ISO codes, and other similar data from the GeoNames premium data set.

Reporting data problems

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

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

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

Other Support

Please report all issues with this code using the GitHub issue tracker.

If you are having an issue with a MaxMind service that is not specific to the client API, please see our support page.

Requirements

This library requires PHP 8.0 or greater.

This library also relies on the MaxMind DB Reader.

Contributing

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

Versioning

The GeoIP2 PHP API uses Semantic Versioning.

Copyright and License

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

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

More Repositories

1

GeoIP2-python

Python code for GeoIP2 webservice client and database reader
Python
1,067
star
2

libmaxminddb

C library for the MaxMind DB file format
C
875
star
3

GeoIP2-java

Java API for GeoIP2 webservice client and database reader
Java
748
star
4

geoipupdate

GeoIP update client code
Go
669
star
5

MaxMind-DB-Reader-php

PHP Reader for the MaxMind DB Database Format
PHP
632
star
6

geoip-api-php

DEPRECATED GeoIP Legacy PHP API
PHP
523
star
7

geoip-api-c

DEPRECATED GeoIP Legacy C API
C
369
star
8

GeoIP2-dotnet

MaxMind GeoIP2 .NET API
C#
331
star
9

web-service-common-php

Shared code for the MaxMind Web Service PHP client APIs
PHP
283
star
10

MaxMind-DB

Spec and test data for the MaxMind DB file format
Go
266
star
11

geoipupdate-legacy

GeoIP update client code
C
258
star
12

geoip-api-python

DEPRECATED GeoIP Legacy Python API
C
233
star
13

GeoIP2-node

Node.js API for GeoIP2 webservice client and database reader
TypeScript
205
star
14

geoip2-csv-converter

GeoIP2 CSV Format Converter
Go
198
star
15

geoip-api-java

DEPRECATED GeoIP Legacy Java API
Java
176
star
16

MaxMind-DB-Reader-python

Python MaxMind DB reader extension
Python
173
star
17

mod_maxminddb

MaxMind DB Apache Module
C
123
star
18

mmdbinspect

look up records for one or more IPs/networks in one or more .mmdb databases
Go
114
star
19

MaxMind-DB-Reader-java

Java reader for the MaxMind DB format
Java
109
star
20

mmdbwriter

Go library for writing MaxMind DB (mmdb) files
Go
100
star
21

MaxMind-DB-Reader-dotnet

.NET Reader for the MaxMind DB Database Format
C#
98
star
22

MaxMind-DB-Writer-perl

Create MaxMind DB database files
Perl
74
star
23

GeoIP2-ruby

Ruby API for GeoIP2 webservice client and database reader
Ruby
55
star
24

minfraud-api-php

PHP API for minFraud Score, Insights, and Factors
PHP
49
star
25

geoip-api-mod_geoip2

DEPRECATED GeoIP Legacy module for Apache 2
C
48
star
26

geoip-api-csharp2

DEPRECATED GeoIP Legacy C# API
C#
47
star
27

MaxMind-DB-Reader-ruby

Ruby reader for the MaxMind DB Database Format
Ruby
45
star
28

getting-started-with-mmdb

A quick guide to writing and reading from your own MMDB databases.
Perl
37
star
29

minfraud-api-python

Python API for minFraud Score, Insights, and Factors
Python
27
star
30

mmdb-from-go-blogpost

Enriching MMDB files with your own data using Go.
Go
23
star
31

ccfd-api-php

Deprecated minFraud Legacy PHP API
PHP
23
star
32

minfraud-api-dotnet

.NET API for MaxMind minFraud Score, Insights, and Factors
C#
19
star
33

GeoIP2-perl

Perl API for MaxMind's GeoIP2 web services and databases
Perl
18
star
34

minfraud-api-java

Java API for minFraud Score, Insights, and Factors
Java
18
star
35

minfraud-api-ruby

Ruby API for minFraud Score, Insights, and Factors
Ruby
14
star
36

mm-geofeed-verifier

Verify the format of a geofeed file, and make some comparisons to data in an MMDB file.
Go
14
star
37

dev-hire-homework

A homework exercise for engineering applicants
Perl
13
star
38

minfraud-api-node

Node.js API for MaxMind minFraud Score, Insights, and Factors
TypeScript
13
star
39

mm-network-analyzer

A program to aid in diagnosing networking issues
Go
12
star
40

MaxMind-DB-Reader-perl

Read MaxMind DB files and look up IP addresses
Perl
12
star
41

mmdbverify

Verifier for the MaxMind DB format
Go
10
star
42

geoip-api-perl

DEPRECATED GeoIP Legacy Perl API
Perl
10
star
43

Stepford

A vaguely Rake/Make/Cake-like thing for Perl - create steps and let a runner run them
Perl
9
star
44

Locale-Country-Multilingual

mapping ISO codes to localized country names
Perl
7
star
45

ccfd-api-java

Deprecated minFraud Legacy Java API
Java
7
star
46

Database-Migrator

Mirror of Database-Migrator on urth.org
Perl
5
star
47

Net-Works

Sane APIs for IP addresses and networks
Perl
5
star
48

MaxMind-DB-Reader-XS

Fast XS implementation of MaxMind DB reader
Perl
5
star
49

ccfd-api-asp

minFraud ASP API
ASP
3
star
50

webservice-paypal-paymentsadvanced

A simple wrapper around the PayPal Payments Advanced web service
Perl
3
star
51

dev-site

Static site generator for https://dev.maxmind.com.
MDX
3
star
52

xgb2code

A converter for xgboost model dumps to code.
Go
3
star
53

geoip-api-mscom

DEPRECATED GeoIP Legacy MS COM API
C
2
star
54

gatling-gen

C++
2
star
55

geolite2-ws-blogpost

Integrating MaxMind's Free and Paid IP Geolocation Web Services (in PHP)
PHP
2
star
56

App-CISetup

Command line tools to generate and update Travis and AppVeyor configs for Perl libraries
Perl
2
star
57

MaxMind-DB-Common-perl

Code shared by the MaxMind DB reader and writer modules
Perl
2
star
58

minfraud-api-perl

Perl API for minFraud Score, Insights, and Factors
Perl
2
star
59

WebService-PivotalTracker

Perl library for the Pivotal Tracker REST API
Perl
2
star
60

fuzzing-workshop

Code for Summit Fuzzing Workshop
Go
1
star
61

Dist-Zilla-PluginBundle-MAXMIND

Perl
1
star
62

TeamCity-Message

Generate TeamCity build messages
Perl
1
star
63

blog-site

Static site generator for https://blog.maxmind.com.
SCSS
1
star
64

api-specs

TypeScript
1
star
65

TAP-Formatter-TeamCity

Emit test results as TeamCity build messages
Perl
1
star