Use GeoIP in PHP

2

The modern way to use GeoIP in PHP is to use MaxMind GeoIP2 PHP API. Go to your project root and install it with composer:

composer require geoip2/geoip2:~2.0

You could see this suggestion:

maxmind-db/reader suggests installing ext-bcmath (bcmath or gmp is required for decoding larger integers with the pure PHP decoder)

OK, let's install php-gmp then:

yum install php-gmp

Go to MaxMind website and download their free GeoLite2 City binary database or buy a more accurate commercial version if you're rich badass.

Unpack the acrhive and put GeoLite2-City.mmdb file where you keep things like that. That's it, now you're ready to use GeoIP in PHP:

require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;

$reader = new Reader('/path/to/GeoLite2-City.mmdb');

$record = $reader->city($_SERVER['REMOTE_ADDR']);

var_dump($record->country->name);
var_dump($record->location->latitude, $record->location->longitude);
var_dump($record->city->name);

There are more stuff you can get from their PHP GeoIP API which you can read about at their GitHub repository

Share this page:

See also how to:

How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP
How to run your PHP or Bash script as root in the most secure way
How to split YAML files and include them into each other with PHP
How to protect your website forms from unwanted spam bots
How to create a well-crafted RSS feed for a website and configure it property