In this tutorial we demonstrate how to get a website visitor's country based on their IP address with PHP using an API call or a local database query.
The easiest way to get a website visitor's country is through an API call, the only prerequisite is the API client class, see the PHP code example below :
<?php
// The free open source DB-IP API client is available on GitHub : https://github.com/dbip/api-client
require "dbip-client.class.php";
// Uncomment the line below and fill in your API key
//DBIP\APIKey::set("YOUR_API_KEY_GOES_HERE");
// Get IP address from the $_SERVER global array, catch forwarded address from proxies
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]) {
$ipAddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
$ipAddress = $_SERVER["REMOTE_ADDR"];
}
// Lookup IP address information
$addrInfo = DBIP\Address::lookup($ipAddress);
// Display results
echo "Visitor ISO-3166-alpha2 country code : {$addrInfo->countryCode}<br />";
echo "Visitor country name : {$addrInfo->countryName}<br />";
In the code example below, we assume you are using the latest database query library and already imported a CSV database to a local MySQL or MariaDB instance :
<?php
// The free open source DB-IP query library is available at : https://db-ip.com/db/format/ip-to-location-isp/csv.html#howto
require "dbip.class.php";
// Connect to the database
$db = new PDO("mysql:host=localhost;dbname=dbip", "mylogin", "mypassword");
// Alternatively connect to MySQL using the old interface
// Comment the PDO statement above and uncomment the mysql_ calls
// below if your PHP installation doesn't support PDO :
// $db = mysql_connect("localhost", "mylogin", "mypassword");
// mysql_select_db("dbip", $db);
// Instanciate a new DBIP object with the database connection
$dbip = new DBIP($db);
// Alternatively instanciate a DBIP_MySQL object
// Comment the new statement above and uncomment below if your PHP
// installation doesn't support PDO :
// $dbip = new DBIP_MySQL($db);
// Get IP address from the $_SERVER global array, catch forwarded address from proxies
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && $_SERVER["HTTP_X_FORWARDED_FOR"]) {
$ipAddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
$ipAddress = $_SERVER["REMOTE_ADDR"];
}
// Lookup IP address information in local database
$addrInfo = $dbip->lookup($ipAddress);
// Show the associated country
echo "Visitor ISO-3166-alpha2 country code : {$addrInfo->country}<br />";
API | DB | |||||||
---|---|---|---|---|---|---|---|---|
Free | Basic | Core | Extended | IP to Country | IP to City | IP to Location | IP to ISP | IP to Location+ISP |
See also : Get visitor country with Javascript
Was this article helpful ? Share it with others by clicking the social media buttons !