How to Get Visitor's Country Using PHP and MySQL Database

In this tutorial, we demonstrate you on how to get visitor's country based on their IP address (IPv4) using PHP programming languages and MySQL database.

Assuming you have the MySQL table setup for IP2Location DB1 database.

Create the sample PHP page below.

<?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();
}
?>

Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.