I have a Javascript function to get the client side date as follows:
var d = new Date();
var month = d.getMonth() + 1;
var thedate =
d.getDate() + "/" +
month + "/" +
d.getFullYear() +
" at "
+ d.getHours() + ":" +
(d.getMinutes()<10?'0':'') + d.getMinutes();
document.write(thedate);
I need this in PHP though, so I tried using this:
$datevar = '
<script>
var d = new Date();
var month = d.getMonth() + 1;
var thedate = d.getDate() + "/" + month + "/" + d.getFullYear() + " at " + d.getHours() + ":" + d.getMinutes();
document.write(thedate);
</script>
';
The piece of code above works fine, BUT only if I echo
it. I don't want to echo
the code. I want to insert it into a log file. This is my code for the log file:
$log_file_name = '1.log';
file_put_contents("$log_file_name, $datevar" , FILE_APPEND);
This returns with literally the code in the log, not the date and time. I would like it to come up with the date.
Can I make it clear that I want the client's date, not the server's
Please, can someone help me with this. I will accept any alternative way to get the client's current date and time. Thank you in advance.
</div>
You need to get the client's time from the browser, then send that to the server with your form submit by adding the value to a hidden input.
HTML:
<input type="hidden" id="timestamp" name="timestamp" value="" />
Your JS will look like this:
<script>
var d = new Date();
document.getElementById("timestamp").value = d.getTime() / 1000;
</script>
Your time.php
file will look like this:
<?php
if (!empty($_POST['timestamp'])) {
$datevar = date('d/m/Y', $_POST['timestamp']) . ' at ' . date('h:i', $_POST['timestamp']) . PHP_EOL;
$log_file_name = '1.log';
file_put_contents($log_file_name, $datevar, FILE_APPEND);
}