Using the free MaxMind IP geolocation tool in PHP
MaxMind offers multiple IP geolocation databases that can be downloaded for free from its website. The 2 main free databases are GeoLite2 Country that allows you to get the country name corresponding to an IP address, and GeoLite2 City to obtain country, region, and city name. The second being the most accurate but also the largest in terms of file size.
The first steps are to sign-up to the MaxMind website and validate your email address. Then you will be able to download the compressed databases from your account page. You will find the geolocation database in the compressed file, named GeoLite-Country.mmdb or GeoLite2-City.mmdb.
Installation of GeoIP2 PHP API can be done through Composer. First, install Composer if it’s not already available on your system:
Then you can install the API and its dependencies:
To finally use this API, you must create a new \GeoIp2\Database\Reader object, passing the path to the MaxMind database file downloaded earlier, then you can query it. Here is an example of its usage with the City database:
Drawbacks of using MaxMind geolocation in PHP
Downloading the MaxMind database and installing its API are additional steps that may put off some of us. Since such a database is updated regularly, you will have to download it again on your servers each time it is updated.
Moreover, the MaxMind files being quite large, you may have a performance loss when several visitors are connected simultaneously on your server.
Alternative to MaxMind: the free Abstract API service
Abstract provides a free geolocation service based on your visitors' IP address, which is very simple to use, does not require installation of any additional components aside from libcurl, and always remain up-to-date without you having to worry about it.
You simply have to create an account on the Abstract website, which will generate your private API key automatically. Then a few lines of code are enough to get the geolocation of your visitors: