A simple IP to Geo Location solution for PHP
I was working on my own use case to find out IP to Geo Location and finally found a free open source service from http://freegeoip.net. It is a community funded project. The service includes GeoLite2 data created by MaxMind
freegeoip.net provides a public HTTP API for software developers to search the geolocation of IP addresses. It uses a database of IP addresses that are associated with cities along with other relevant information like time zone, latitude, and longitude.
You're allowed up to 15,000 queries per hour by default. Once this limit is reached, all of your requests will result in HTTP 403, forbidden, until your quota is cleared.
The freegeoip web server is free and open source so if the public service limit is a problem for you, download it and run your own instance.
The HTTP API takes GET requests in XML, JSON, CSV format.
While making an API call, if no IP or hostname is provided, then your own IP is looked up.
To make this API call simple and organized I decided to create a package for my own use case as well as for the community people to use it as open source. It is available to view it on Github.
You can install the package via composer.
composer require sudiptpa/geoip
This package only supports
json format for now.
Here are a few examples on how you can use the package:
$geo = new Sujip\GeoIp\GeoIp($ip); $geo->country(); $geo->city(); $geo->region(); $geo->formatted(); // Jawalakhel, Central Region, Nepal
Also, have a look at the source code of
Sujip\GeoIp\GeoIp to discover the methods you can use via GitHub.
Thanks for reading up to the end. If you have any feedback please leave your comments below. Feel free to share with friends if you like it.