Display Visitor's Local Time Using PHP and BIN Database

In this tutorial, we demonstrate you on how to display visitor's local time based on their IP address using PHP programming languages and IP2Location BIN database. This tutorial uses the IP2Location module, available at http://www.ip2location.com/developers/php, to query IP information from BIN database. Free BIN databases are available for download at IP2Location LITE database.

 

Step 1: Download IP2Location LITE database, unzip the file and copy the BIN database (.bin extension) into the same directory of where you save your sample code.

Step 2: Download IP2Location PHP class module, unzip the file and copy IP2Location.php into the same directory of where you save your sample code.

Step 3: Run the below sample code.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(0);

require_once('IP2Location.php');

// Standard lookup with no cache
$loc = new IP2Location('databases/DB24-SAMPLE.BIN', IP2Location::FILE_IO);

/*
   Cache whole database into system memory and share among other scripts & websites
   WARNING: Please make sure your system have sufficient RAM to enable this feature
*/
//$loc = new IP2Location('databases/IP-COUNTRY-SAMPLE.BIN', IP2Location::SHARED_MEMORY);

/*
   Cache the database into memory to accelerate lookup speed
   WARNING: Please make sure your system have sufficient RAM to enable this feature
*/
//$loc = new IP2Location(ROOT . 'databases/IP-COUNTRY-SAMPLE.BIN', IP2Location::MEMORY_CACHE);

$ip = $_SERVER['REMOTE_ADDR'];

$utc_time = gmdate("H:i:s");
$utc_h = explode(':', $utc_time);
$time_zone = $loc->lookup($ip, IP2Location::TIME_ZONE);
$country_code = $loc->lookup($ip, IP2Location::COUNTRY_CODE);
if (strcmp($time_zone, "-") == 0) {
	$localdate = $utc_time;
}
else {
	$time = explode(':', $time_zone);

	if ($utc_h[0] + $time[0] < 0) {
		$hour = $utc_h[0] + 24 + $time[0];
	}
	elseif ($utc_h[0] + $time[0] >= 24) {
		$hour = $utc_h[0] + $time[0] - 24;
	}
	else {
		$hour = $utc_h[0] + $time[0];
	}
	
	$localdate = $hour . gmdate(":i:s");	
}

date_default_timezone_set("Asia/Kuala_Lumpur");
$date = date_create($localdate);
echo 'Country Code: ' . $country_code . '
'; echo 'Local Time: ' . date_format($date, "H:i:s") . ' (' . $time_zone . ').
'; echo 'Server Time: ' . strftime("%H:%M:%S (%z)") . '
'; echo 'UTC Time: ' . gmdate("H:i:s (e)") . '
'; ?>

Download demo project : Display visitors local time.


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.