Introduction
In this article I will walk you through on How To Detect Country From IP Address In PHP.
Did you know that PHP offers an easy way to detect the visitors country from the IP address without writing code?
I will break this topic in the following way:
- How to setup your system to get started
- Full code example on how to implement and find the country of your visitors
- Putting the code to test and seeing if it works from different origins
This is a complete and easy to follow guide with step by step instructions providing all source code needed.
I’m going to keep all the steps simple and straight to the point to avoid you have to spend endless hours debugging or trying to figure out why things aren’t working. Hey if I missed something you are always welcome to ping me on twitter or via my contact page.
This guide is specifically designed for those that want to get straight into action with a lightweight code that gets the job done.
I have successfully used this in various projects over the years and it has worked pretty well without needing any changes.
I have been working in the Software industry for over 23 years now and I have been a software architect, manager, developer and engineer. I am a machine learning and crypto enthusiast with emphasis in security. I have experience in various industries such as entertainment, broadcasting, healthcare, security, education, retail and finance.
All source code associated with this article can be found in my GitHub here.
How To Setup PHP
Note if you already have PHP installed in your system you can skip this section entirely and move to the fun part.
First we will quickly focus on how to setup PHP locally to get started. Since this is an over-discussed topic I’m only going to cover it briefly here to save some of your time from snooping around online.
I will also tell you how to set it up and debug this locally on your system without much effort.
How To Setup PHP In Windows
I have documented this extensively in this article before which you can find here on my Trivia game (note this will take you directly to the setup section of it). If you want you can use it as a reference.
How To Setup PHP In Mac
How To Install Brew In Mac
In this guide we will be using a Mac computer. First you’d need to install brew in your system which you can find here. To install it simply run the following command:
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
This will walk you through some requirements and questions and you should be all set. Once it’s installed you can simply invoke the brew command to ensure things work it should look something like this:
$ brew --version Homebrew 3.3.13 Homebrew/homebrew-core (git revision 12acdcd092b; last commit 2022-02-05) Homebrew/homebrew-cask (git revision 83cc998631; last commit 2022-02-05)
Don’t worry too much on the versioning for now this can be anything at the time you use.
How To Use Brew To Install PHP
Now that we have brew installed we can simply invoke the brew command to install PHP on our system everything is automated and you don’t really need to do much about it.
$ brew install php ..... ==> php The php.ini and php-fpm.ini file can be found in: /opt/homebrew/etc/php/8.1/ To restart php after an upgrade: brew services restart php
And to verify we installed it successfully we can run the command to get the version:
$ php --version PHP 8.1.2 (cli) (built: Jan 21 2022 04:34:05) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.2, Copyright (c) Zend Technologies with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies
How To Setup PHP In Linux
And to quickly address Linux so it’s not left out things are fairly simple here to install it simply use your operating systems manager to get going.
# Debian Based operating systems such as Ubuntu $ apt install php # Redhat based operating systems such as Fedora/CentOS $ yum install php
How to Detect Country from IP Address in PHP
Now that we have PHP all setup in our system we simply can start editing our code and making sure this works. For this we will be hosting it locally just to test it out first and see what results we yield. Once we verify the code is not giving any errors we will test it with some IPs that we know and see if it’s working fine.
How To Install MaxMind GeoIP For PHP
In order to get PHP going we need to use the help of an external library provided by Maxmind which you can find here.
So before we actually use the code we need to download a few dependencies and initialize our environment.
The first thing we need to do is download a helper tool called composer which you can get like this:
$ curl -sS https://getcomposer.org/installer | php All settings correct for using Composer Downloading... Composer (version 2.2.6) successfully installed to: /Users/alex/code/unbiased/php-detect-country-from-ip/composer.phar Use it: php composer.phar
So now that we have composer setup all we need to do is initialize locally our GeoIP database. In order to do that simply getch geoip-2 dependency using the following command:
$ php composer.phar require geoip2/geoip2:~2.0 ./composer.json has been created Running composer update geoip2/geoip2 Loading composer repositories with package information Updating dependencies Lock file operations: 4 installs, 0 updates, 0 removals - Locking composer/ca-bundle (1.3.1) - Locking geoip2/geoip2 (v2.12.2) - Locking maxmind-db/reader (v1.11.0) - Locking maxmind/web-service-common (v0.8.1) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 4 installs, 0 updates, 0 removals - Downloading composer/ca-bundle (1.3.1) - Downloading maxmind/web-service-common (v0.8.1) - Downloading maxmind-db/reader (v1.11.0) - Downloading geoip2/geoip2 (v2.12.2) - Installing composer/ca-bundle (1.3.1): Extracting archive - Installing maxmind/web-service-common (v0.8.1): Extracting archive - Installing maxmind-db/reader (v1.11.0): Extracting archive - Installing geoip2/geoip2 (v2.12.2): Extracting archive 1 package suggestions were added by new dependencies, use `composer suggest` to see details. Generating autoload files 1 package you are using is looking for funding. Use the `composer fund` command to find out more!
As you can see above basically it fetches all the libraries needed for you and installs them in the local directory for you.
The important file we will be making use from is the autoload.php library which got generated from the previous command. Before we proceed into the code you can verify this got installed running this:
$ ls LICENSE README.md composer.json composer.lock composer.phar vendor $ ls vendor/autoload.php vendor/autoload.php
If the file exits you are good to go and proceed into the next step of downloading the database file.
In order to do that you can get it from MaxMinds page it’s a free download make sure you look for the GeoIP Lite City database the filename is GeoLite2-City.mmdb
Now we are ready to start coding our example to find the origin of some IPs.
Example Code To Get Country and City in PHP
Let’s dive right into the code quickly and go line by line and explain what is happening here.
<?php require_once 'vendor/autoload.php'; use GeoIp2\Database\Reader; $reader = new Reader('/Users/user/code/unbiased/php-detect-country-from-ip/GeoLite2-City.mmdb'); $ip_list = array( '8.8.8.8', '1.1.1.1', '139.178.84.217', ); foreach ($ip_list as $ip){ $record = $reader->city($ip); print("Information for IP: $ip\n"); print("Country Short Code: " . $record->country->isoCode . "\n"); print("Country Name: " . $record->country->name . "\n"); print("Latitude: ". $record->location->latitude ." \n"); print("Longitude: ". $record->location->longitude ."\n"); print ("====================================\n"); } ?>
Basically our code is split into three main pieces:
- Initializing of library: This can be seen in the first few lines where we import the autoload dependency we previously generated. Note here you will need to adjust as an absolute path the location of the MaxMind database you previously downloaded.
- Defining A Sample: We producing a sample of IPs we want to query, this is defined as the array we have above.
- Printing Out Results: We simply print out the information we find for each IP.
We are re-using essentially the reader object which contains the information from the MaxMind library that we previously initialized. This can be re-used across all of our IPs and we don’t need to make a new one each time saving some processing time.
All the code above can be found in the GitHub Repo here. Do note I have excluded the Max Mind database as this is based on a free license key which you can acquire from the website if you followed the step earlier, due to licensing reasons I cannot include it here.
Testing The Output Of Execution Of The Code
Now that we went over the code lets try to do a run and see if it performs as expectant.
$ php ./php-get-country-city-from-ip.php Information for IP: 8.8.8.8 Country Short Code: US Country Name: United States Latitude: 37.751 Longitude: -97.822 ==================================== Information for IP: 1.1.1.1 Country Short Code: AU Country Name: Australia Latitude: -33.494 Longitude: 143.2104 ==================================== Information for IP: 139.178.84.217 Country Short Code: US Country Name: United States Latitude: 32.7767 Longitude: -96.805 ====================================
As it can be seen above it’s processing one IP at a time from the array that we have defined. For simplicity in this example I used:
- Google DNS server (8.8.8.8)
- Cloudflare’s DNS server (1.1.1.1)
- Kernel.org website IP at the time
The script successfully executed and found the Country along with the longitude and latitude of each of the IPs we provided.
Conclusion
If you found the How To Detect Country From IP Address In PHP useful and you think it may have helped you please drop me a cheer below I would appreciate it.
If you have any questions, comments please post them or on my twitter account, I check periodically and try to answer them in the priority they come in. Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.
Which is your favorite PHP library to use for geolocation identification?
My personal favorite is the Max Mind PHP library it’s lightweight and it’s easy to get going.
If you would like to learn more about other stuff I’ve done in PHP you can check my article on building a Trivia app below: