0

how to send browser time to MySQL server for save through php. I search lot's of time on the internet, but I did not find a good answer. suppose my browser time is 17-Sep-2018 3:10:55

So how can I store this in my database. I Use NOW(), DATE but nothing the write answer.thanx in advanced.

Sourab Bhowmik
  • 85
  • 1
  • 1
  • 7
  • 4
    Why do you care about the browser's time? Is this for timezone support or something? – ceejayoz Sep 16 '18 at 21:44
  • Javascript... PHP runs on the server, after being executed and compiled the user only sees the rendered page. Javascript in the other hand is executed on the local user's browser. – Sam Sep 16 '18 at 21:46
  • yes, you can say ceejayoz – Sourab Bhowmik Sep 16 '18 at 21:46
  • Could you echo html that uses js to get the time and then send that via xmlhttp request? Kinda hacky, but does the client-side journey for you? I think that's what Samuel might have been saying, to be fair. – Sundance.101 Sep 16 '18 at 21:54

2 Answers2

1

You will have to use Javascript; PHP is executed on the server - which is not the same as the user's browser or location.

For example:

(function() {
  var url = '/some/file.php?date=' + new Date();

  fetch(url, {
    method: 'GET',
    mode: 'no-cors'
  })
  .then(response() => console.log(response))
  .catch(error => console.error('Could not complete request:', error));
})();

Then in the Server you can process the request:

<?php

// request date contains the date from our JS request

if( $_REQUEST['date'] )
{
  // format it how you want it
  $date = date('j M Y h:i:s a', $_REQUEST['date']);

  // check and make sure variable exists
  if( $date )
  {
    // connect to mysql (this is not recomended... better to use some sort of library)
    $mysql = new mysqli('localhost', 'root', '', 'site');

    // safely store it with prepared statements
    $stmt = $mysql->prepare('INSERT INTO visits (visist_time) VALUES (?)');
    if($stmt = $stmt->bind_param('d', $date))
    {
      // this will execute the query
      $stmt->execute();
    }
  }
}

This is not a perfect answer; I am not sure why you want to get a timestamp for users who visit, but that will in theory be able to record timestamps every time the JS script is loaded.

Sam
  • 2,856
  • 3
  • 18
  • 29
0

Don't store the browser time - it could easily be incorrect, and will wreak havoc on users who travel between timezones as well. (If I go visit Australia, all my appointments in your database would suddenly be 14 hours off...)

Instead, you should store the server's time - which should always be correct using something like NTP - and in UTC. When you need to show a date to the user, you can use JavaScript to convert the timestamp into the correct time based on the browser's current GMT offset.

Another option is having the user provide their chosen timezone as a setting, and converting to that.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368