James Bachini

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:

Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.