In modern web development, capturing visitor geolocation data is essential for content localization, targeted marketing, fraud prevention, and regional analytics. Fortunately, extracting this data is straightforward using the IP2Location database.
This tutorial demonstrates how to retrieve a visitor’s country from their IPv4 address using PHP and a MySQL database.
Prerequisites #
Before proceeding, ensure you have:
- A working PHP environment.
- The IP2Location DB1 (Country) dataset imported into a MySQL table.
Note: Because IP addresses are stored as long integers for optimized database indexing, our script will use PHP’s ip2long() function to convert the visitor’s IP before querying the database.
The PHP Implementation #
Create a file named index.php (or add this snippet to your existing page) to detect and display the visitor’s country:
PHP
<?php
//Configure the MySQL connection
$host = 'localhost';
$user = 'root';
$password = 'YOUR_PASSWORD';
$database = 'ip2location_database';
$table_name = 'ip2location_db1';
//Get the visitor IP address
$ip = $_SERVER['REMOTE_ADDR'];
//In case you are testing locally with 127.0.0.1,
//you can uncomment the below line to assign the IP address
//to 8.8.8.8 (or whatever) for your testing.
//$ip = '8.8.8.8';
try{
//Create and perform the SQL query using the PDO
$db = new PDO('mysql:host=' . $host . ';dbname=' . $database . ';charset=utf8', $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$st = $db->prepare('SELECT * FROM `' . $table_name . '` WHERE INET_ATON(:ip) <= ip_to LIMIT 1');
$st->execute(array(':ip'=>$ip));
$row = $st->fetch(PDO::FETCH_ASSOC);
//Print out the result
var_dump($row);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
