Display Visitor's Local Time Using PHP and BIN Database

Language

This sample code can be used to display visitor's local time based on their IP address using PHP programming languages and IP2Location BIN database. Free database is provided by IP2Location LITE at http://lite.ip2location.com/
  1. <?php
  2. ini_set('display_errors', 1);
  3.  
  4. require_once('IP2Location.php');
  5. $loc = new IP2Location('databases/DB24-SAMPLE.BIN', IP2Location::FILE_IO);
  6.  
  7. //$loc = new IP2Location('databases/IP-COUNTRY-SAMPLE.BIN', IP2Location::SHARED_MEMORY);
  8.  
  9. //$loc = new IP2Location(ROOT . 'databases/IP-COUNTRY-SAMPLE.BIN', IP2Location::MEMORY_CACHE);
  10.  
  11. $ip = $_SERVER['REMOTE_ADDR'];
  12.  
  13. $utc_time = gmdate("H:i:s");
  14. $utc_h = explode(':', $utc_time);
  15. $time_zone = $loc->lookup($ip, IP2Location::TIME_ZONE);
  16. $country_code = $loc->lookup($ip, IP2Location::COUNTRY_CODE);
  17. if (strcmp($time_zone, "-") == 0) {
  18. $localdate = $utc_time;
  19. }
  20. else {
  21. $time = explode(':', $time_zone);
  22.  
  23. if ($utc_h[0] + $time[0] < 0) {
  24. $hour = $utc_h[0] + 24 + $time[0];
  25. }
  26. elseif ($utc_h[0] + $time[0] >= 24) {
  27. $hour = $utc_h[0] + $time[0] - 24;
  28. }
  29. else {
  30. $hour = $utc_h[0] + $time[0];
  31. }
  32.  
  33. $localdate = $hour . gmdate(":i:s");
  34. }
  35.  
  36. date_default_timezone_set("Asia/Kuala_Lumpur");
  37. $date = date_create($localdate);
  38. echo 'Country Code: ' . $country_code . '<br>';
  39. echo 'Local Time: ' . date_format($date, "H:i:s") . ' (' . $time_zone . '). <br>';
  40. echo 'Server Time: ' . strftime("%H:%M:%S (%z)") . '<br>';
  41. echo 'UTC Time: ' . gmdate("H:i:s (e)") . '<br>';
  42. ?>

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Submitted byJessicamorris (not verified)on Tue, 05/10/2022 - 12:50

Very well-written article! To support the demand for PHP development, it is safe to say that PHP has been the most famous and most used framework today. The efficient and sturdy structure of this framework has made it what it is today. According to W3Techs' data, PHP is used by 78.9% of all websites with a known server-side programming language. Constantly, top PHP development company in the USA are growing rapidly with the increasing demand of custom app development.

Add new comment