How to get visitor’s country from their IP with PHP?

Spread the love

Sometimes, we want to get visitor’s country from their IP with PHP.

In this article, we’dll look at how to get visitor’s country from their IP with PHP.

How to get visitor’s country from their IP with PHP?

To get visitor’s country from their IP with PHP, we use the MaxMind GeoIP library.

For instance, we write

$gi = geoip_open("GeoIP.dat", GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER["REMOTE_ADDR"]);
geoip_close($gi);

to open the GeoIP.dat file with the IP data.

Then we call geoip_country_code_by_addr with $gi and the visitor IP address we get from $_SERVER["REMOTE_ADDR"] to get the $country.

Once we’re done, we call geoip_close to close the $gi handle.

Conclusion

To get visitor’s country from their IP with PHP, we use the MaxMind GeoIP library.

Leave a Reply

Your email address will not be published.