Hi,

I am looking for a PHP script that can take an ip address and return the country where that ip address belongs to.
If you know or have been using such a script, please let me know.

Thanks

Dani AI

Generated

If you want to avoid a third-party call (as noted can add latency/uptime risk), use a local IP-to-country database. The free GeoLite2 Country database from MaxMind is fast, IPv4/IPv6-aware, and easy to query from PHP with their official library. You create a free MaxMind account to download it and keep it updated. See GeoLite2 free geolocation data and the GeoIP2 PHP API. (dev.maxmind.com)

<?php
require 'vendor/autoload.php';               // composer require geoip2/geoip2
use GeoIp2\Database\Reader;

function clientIp(): string {
  $ip = $_SERVER['REMOTE_ADDR'] ?? '';
  // If you sit behind a trusted reverse proxy, replace the next block
  // with your allowlisted proxy logic before trusting X-Forwarded-For.
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $cand = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    if (filter_var($cand, FILTER_VALIDATE_IP)) $ip = $cand;
  }
  return $ip;
}

$ip = clientIp();

// Private/reserved? Treat as unknown country.
$isPublic = filter_var($ip, FILTER_VALIDATE_IP,
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
if (!$isPublic) { echo 'XX'; exit; }

$reader = new Reader('/path/to/GeoLite2-Country.mmdb');
try {
  echo $reader->country($ip)->country->isoCode ?? 'XX';
} catch (\GeoIp2\Exception\AddressNotFoundException $e) {
  echo 'XX';
}

For and seeing XX: that typically means the IP is private (e.g., RFC1918 ranges like 10.0.0.0/8 or 192.168.0.0/16), special/reserved (loopback, link-local, test nets, etc.), or simply not in your copy of the database yet. Validate the client IP, skip private/reserved ranges, and update the GeoLite2 database regularly to reduce misses. References: RFC 1918 private address ranges and RFC 6890 special-purpose addresses. (rfc-editor.org)

Recommended Answers

All 6 Replies

Hi,

I am looking for a PHP script that can take an ip address and return the country where that ip address belongs to.
If you know or have been using such a script, please let me know.

Thanks

HI alpha2006,

What you need first is to get a database that matches IPs to countries/cities/locations.

Since IP to country is used alot in log analysis, you probably already have one installed on your php server if you rent one. Cpanel (common web based linux server administration panel) for example usually comes together with Awstats (analyses raw linux log files) which has an IP-country database.

Theres a couple listed at the ODP under log analysis:

You can also find some at sourceforge.net or hotscripts.com

The php script of course will be specific to the database structure of the IP-to-Country Database you are using. Some databases will already have premade scripts too.

An easy way to get IPs converted to countries withought setting up the IP-to-country database and writing the php script for the db, is to use a webservice that does this for you and provides an API interface to geocoding (converting data to a location) IP addresses.

I've used http://www.hostip.info/ and they are really easy to use. Theres many others too.

With http://www.hostip.info/ if you dont require much functionality, you can just use a simple html based API for converting an IP to the contry flag.

Exaple:

<A HREF="http://www.hostip.info">
 <IMG SRC="http://api.hostip.info/flag.php" BORDER="0" ALT="IP Address Lookup">
</A>

Will automatically show the visitors contry flag.

To get just the contry via http, you can send http://www.hostip.info a get request to the url http://api.hostip.info/country.php

Example:

http://api.hostip.info/country.php

You can test this by clicking the link above.

The request to http://api.hostip.info/country.php returns the Country Code/Abbrev. in the HTTP Content of their HTTP Response.
So retrieving it via php is quite easy.

example:

<?php

$country = file_get_contents('http://api.hostip.info/country.php');
echo $country;


?>

This however will return your server location, since the IP would be set as your server IP.

So you'll have to get the visitors IP via the REMOTE_ADDR which is available in PHP as a "predefined variable". Then append their IP to the country endpoint of their API.

Example:

http://api.hostip.info/country.php?ip=xxx.xxx.xxx.xxx

Example PHP:

<?php

$country = file_get_contents('http://api.hostip.info/country.php?ip='.$_SERVER['REMOTE_ADDR'];
echo $country;

?>

Note: usually you wouldn't just use $_SERVER as that is sent to your server as a HTTP Header, and can be tampered with (unlikely but still). So you should treat it as user submitted data and "clean" it. Also, theres a few different predefined variables that get the IP, for different setups, theres a few functions out there just for getting the right one.

Using a web services is easier I believe, and avoids having a huge database and load on your server, but it is a bit slower and dependant on the availablility of the remote server that you are connecting to.

Hope that starts you off...
:)

I've only just started looking for the code that would do this and your reply was a real find. It worked like a charm. Thanks a whole bunch!

But it returns me XX? What could be the reason?

am getting the output as xx.
please help me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.