Jan 8, 2013

PHP: shortest and easiest GeoIP (IP to Country)

Without using a database of IP addresses or an "external API" (not completely true), this is the shortest method of determining the country of an IP addresss.

The one-liner issues a shell_exec() to the whois command and parses the two letter country code from it.

if(preg_match('/^(\d+\.?){4}$/',$ip)) {
  $country = trim(shell_exec('whois '.$ip.' -H | grep country | awk \'{print $2}\''));
}

The preg_match() is of course optional, but for your own good, because as you may know, shell_exec() is VERY DANGEROUS.

Note: This does not work on all versions of WHOIS!

Also note that there is a daily query limit to the RIPE.NET database, so it's good to cache the results. It's not like that information gets changed often.

1 comment:

Claude "CodeAngry" Adrian said...

You might want to replace the regexp with a filter_var as PHP does everything for you. Plus the regexp isn't really validating an IP properly. Aside from that, it does it's job of filtering input to shell_exec.

Querying an external service or launching new processes can become a bottleneck for your site's performance. Such actions should only be performed in background tasks (cronjobs) where the user does not want, assume, expect your site to load as fast as possible.

Checkout my ip to country php script as an alternative.