Table of Contents

To retrieve a visitor’s country based on their IP address in PHP, you have a few options. Let’s explore some methods:

Using Free Web Services:

  • If you prefer a simple solution, you can use free web services like ipinfo.io or geoplugin.net. These services return JSON data with country information.
  • Here the example for geoplugin.net:
<?php 
// PHP code to obtain country, city,
// continent, etc using IP Address

$ip = $_SERVER['REMOTE_ADDR'];

// Use JSON encoded string and converts
// it into a PHP variable
$ipdat = @json_decode(file_get_contents(
"http://www.geoplugin.net/json.gp?ip=" . $ip));

echo 'Country Name: ' . $ipdat->geoplugin_countryName . "\n";
echo 'City Name: ' . $ipdat->geoplugin_city . "\n";
echo 'Continent Name: ' . $ipdat->geoplugin_continentName . "\n";
echo 'Latitude: ' . $ipdat->geoplugin_latitude . "\n";
echo 'Longitude: ' . $ipdat->geoplugin_longitude . "\n";
echo 'Currency Symbol: ' . $ipdat->geoplugin_currencySymbol . "\n";
echo 'Currency Code: ' . $ipdat->geoplugin_currencyCode . "\n";
echo 'Timezone: ' . $ipdat->geoplugin_timezone;

?>
  • Here’s an example using ipinfo.io:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$url = "http://ipinfo.io/$ip/json";
$response = file_get_contents($url);
$data = json_decode($response, true);

$countryName = $data['country'];
echo "Visitor's country: $countryName";
?>

Using GeoIP Libraries:

  • MaxMind GeoIP: MaxMind provides a GeoIP database that maps IP addresses to geographical locations. You can use their PHP library to get detailed information, including the country name. Here’s an example using MaxMind’s GeoIP2 PHP library:
<?php
require 'vendor/autoload.php'; // Include the GeoIP2 library

$reader = new GeoIp2\Database\Reader('path/to/GeoLite2-Country.mmdb');
$ip = $_SERVER['REMOTE_ADDR'];

try {
$record = $reader->country($ip);
$countryName = $record->country->name;
echo "Visitor's country: $countryName";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>

Note: You’ll need to download the GeoLite2-Country database and adjust the path accordingly.

Using External APIs:

    • There are several free and paid APIs that provide IP geolocation data. One such option is ipstack. You can sign up for a free account and use their API to get country information. Here’s an example:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$api_key = 'your_api_key_here';

$url = "http://api.ipstack.com/$ip?access_key=$api_key";
$response = file_get_contents($url);
$data = json_decode($response, true);

$countryName = $data['country_name'];
echo "Visitor's country: $countryName";
?>