Setting up Maxmind GEOIP2 Legacy Database with PHP or Javascript

This is the php code I use to access geoip data from Maxmind’s geoip database:

$gpath = getcwd() . “/GeoIPCity.dat”;
if (isset($_SERVER[‘REMOTE_ADDR’])) { $myip = $_SERVER[‘REMOTE_ADDR’]; }
$gi = geoip_open($gpath,GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,$myip);
$city = $record->city;
$countrycode = $record->country_code;

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”;

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:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *