Coding For Online Success

GeoIP Scripts PHP and JavaScript


Last week I was reading Danger Brown’s “Easy geo/ip script to be sneaky with“, and oddly enough just days before that I was working on a server side solution to do the same thing. His example is using maxmind’s geoip.js script to determine where your referring IP address is coming from. Here is the script to do this client side using javascript.

span class=”st0″>"JavaScript" src="""JavaScript""JavaScript"

MaxMind creates IP geolocation services and offers this server for free or at a cost, depending on your needs. I wanted to be able to add some conditionals in my example, and have this be available for bots and browsers that do not support javascript. The solution is to grab the geoip information serverside, and then generate the output in HTML using PHP.

To do this you will need to make sure that your version has the pecl-geoip extension available. I’m using dev-php5/pecl-geoip. After this extension is built and is available to your PHP installation, you can simple call this geoip_record_by_name() function and pass a valid IP address.

For example, this is looking up a Google IP:

span class=”st0″>’′

$record is a array that contains some useful information about that IP:

span class=”st0″>’country_code’ => string ‘US’ (length=2)
‘region’ => string ‘CA’ (length=2)
‘city’ => string ‘Mountain View’ (length=13)
‘postal_code’ => string ‘94043’ (length=5)
‘latitude’ => float 37.4192008972
‘longitude’ => float -122.057403564
‘dma_code’ => int 807
‘area_code’ => int 650

I had some problems with a missing GeoLiteCity.dat file that was missing. LiteCity is free, and any additional dats will cost money. Luckily, MaxMind had a download here:

If you need function definitions, you can view them here. I was glad that I found this forum entry, pecl documentation and examples usually suck pretty bad:


Leave a Reply

Required fields are marked *.

CommentLuv badge

This site uses Akismet to reduce spam. Learn how your comment data is processed.