• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / PHP geo targeting with the geoip functions

PHP geo targeting with the geoip functions

The PHP GeoIP library makes it easy to look up country codes and names from an IP address. It’s not enabled/installed by default so you need to install it before you can access these functions. I’ve already posted about how to do this with Debian and other Linux distros will be similar.

Get a country code from an IP address

There are two functions for getting a country code from an IP address: one returns a 2 letter country code and the other a 3 letter country code. To get the country code for a specific IP address just pass it as the only parameter. The examples below use the IP address of my office.

echo geoip_country_code_by_name('121.98.150.81');
echo geoip_country_code3_by_name('121.98.150.81');

The first example would echo "NZ" and the second "NZL" because my office is in New Zealand.

To get the country code for the current visitor’s IP address use the following:

echo geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
echo geoip_country_code3_by_name($_SERVER['REMOTE_ADDR']);

Get a country name from an IP address

The geoip_country_name_by_name() function does the same as the above but returns the country’s name. For example:

echo geoip_country_name_by_name('121.98.150.81');

The above would echo out "New Zealand".

And the example using REMOTE_ADDR:

echo geoip_country_name_by_name($_SERVER['REMOTE_ADDR']);

A note aboute REMOTE_ADDR

Note that using REMOTE_ADDR is not entirely reliable as it may be the IP address of a proxy server. You can use $_SERVER[‘HTTP_X_FORWARDED_FOR’] if it is set instead which should solve this issue some of the time if the visitor is connecting via a proxy.

Check Out These Related posts:

  1. How to update the GeoIP.dat file on Debian 5
  2. Using CSS letter-spacing to space out titles
  3. How to enable the PHP GeoIP functions on Debian 5
  4. PHP GeoIP functions throw notices if the IP address is not found

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap