This is the php code I use to access geoip data from Maxmind’s geoip database:
<?php
$gpath = getcwd() . “/GeoIPCity.dat”;
if (isset($_SERVER[‘HTTP_X_FORWARDED_FOR’])) { $myip = $_SERVER[‘HTTP_X_FORWARDED_FOR’]; }
if (isset($_SERVER[‘REMOTE_ADDR’])) { $myip = $_SERVER[‘REMOTE_ADDR’]; }
include(“./geoipcity.inc”);
$gi = geoip_open($gpath,GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,$myip);
$city = $record->city;
$countrycode = $record->country_code;
geoip_close($gi);
echo ‘countrycode = “‘.$countrycode.’”;
city = “‘.$city.’”;’;
?>
It sets city and countrycode vars, the two lines you’ll need to edit and point to your own server locations are lines 1 and 4:
$gpath = getcwd() . “/GeoIPCity.dat”;
include(“./geoipcity.inc”);
You should then be able to either print out vars straight from php like the echo command at the end or include that as javascript file with:
<script src=”whateveryoucalledthephpfileabove.php” ></script>
Additional Notes:
When accessing the user IP address from PHP variables it is a good idea to look for both $_SERVER[‘HTTP_X_FORWARDED_FOR’] and $_SERVER[‘REMOTE_ADDR’] because different servers store the variable differently and this can cause problems when migrating. Lines 2 and 3 do that above using the isset function.
You can find the different country codes used by Maxmind here:
http://www.jamesbachini.com/what-was-that-country-code/