Display Visitor’s Local Time Using PHP and BIN Database PHP Script


Display Visitor’s Local Time Using PHP and BIN Database PHP Script

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/

 

 

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    set_time_limit(0);
     
    require_once('IP2Location.php');
    $loc = new IP2Location('databases/DB24-SAMPLE.BIN', IP2Location::FILE_IO);
     
    //$loc = new IP2Location('databases/IP-COUNTRY-SAMPLE.BIN', IP2Location::SHARED_MEMORY);
     
    //$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 . '<br>';
    echo 'Local Time: ' . date_format($date, "H:i:s") . ' (' . $time_zone . '). <br>';
    echo 'Server Time: ' . strftime("%H:%M:%S (%z)") . '<br>';
    echo 'UTC Time: ' . gmdate("H:i:s (e)") . '<br>';
    ?>

 

 

Read Me

 

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *