3

I am using this simple line of code to get the current date into my var.

$datevar = date("Y-m-d"); 

But this gives me the current date of the server not of the user. I have a page where users from all over the globe log in, so this actualy is an issue. Anyway I can get it with php or would I need to get js involved?

Mike Pala
  • 766
  • 1
  • 11
  • 39
  • 6
    You need js, the only other reliable way would be if browsers sent that information as a standard request header, and they don't. – Alex K. Feb 14 '18 at 16:31
  • 1
    Seems related to this https://stackoverflow.com/questions/4746249/get-user-timezone – bennes Feb 14 '18 at 16:34
  • @bennes your link refers to a duplicate itself :P –  Feb 14 '18 at 16:44
  • 1
    I dislike it when high voted questions and answers, get later marked as a duplicate of some low-rate unrelated garp. – IncredibleHat Feb 14 '18 at 17:04

1 Answers1

3

You can do it by two way. Send it from browser to server by Javascript OR use one of "Location-by-IP" services

Javascript solution you can find here get user timezone (thanks to @bennes)

But If you want to do it only on server side you can use this service https://timezoneapi.io/developers/ip-address

Here is example

// Get IP address
$ip_address = getenv('HTTP_CLIENT_IP') ?: 
getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: 
getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: 
getenv('REMOTE_ADDR');
// Get JSON object
$jsondata = file_get_contents("http://ip-api.com/json/" . $ip_address); 
// Decode
$data = json_decode($jsondata, true);

// Example: Get the city parameter
echo "City: " . $data['city'] . "<br>";
// Example: Get the users time
echo "Time: " . $data['timezone'] . "<br>";

Of course better to save offset to $_SESSION. Otherwise it'll generate outgoing request each time.

So you need someting like

session_start();
if (!isset($_SESSION['offset_hours'])) {
    $ip_address = getenv('HTTP_CLIENT_IP') ?: getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: getenv('REMOTE_ADDR');
    $jsondata = file_get_contents("http://timezoneapi.io/api/ip/?" . $ip_address);
    $data = json_decode($jsondata, true);
    if($data['meta']['code'] == '200'){
        $_SESSION['offset_hours']= $data['data']['datetime']['offset_hours'];
    }    
}


echo $_SESSION['offset_hours']; // Here is offset in hours
ABelikov
  • 613
  • 5
  • 10