0

I've this code that works fine to get the user Timezone and echo in php. There's also an alert message before.

<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script> <script> var timezone =
Intl.DateTimeFormat().resolvedOptions().timeZone; alert(timezone);
</script>
<?php
$time= "<script>document.writeln(timezone);</script>";
echo $time;

I want to store this echo in the file time.txt

I've tried with this:

$file_name = 'time.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'w') or die('Cannot open file: '.$file_name);
// write name to the file
fwrite($myfile, $time);
// close the file
fclose($myfile);

but it doens't work .

Any solutions?

1 Answers1

2

It seems like what you want is for PHP to write the file with the result of the timezone variable, i.e. that it would be a text file with the name of a timezone in it.

Probably what you are seeing is PHP writing that JavaScript line instead, i.e. <script>document.writeln(timezone);</script>

Right?

What's happening is PHP executes completely before JavaScript is run. Your first example is working because PHP executes, including the writing of a line of JavaScript, and then JavaScript executes, including that line, and you see the result.

What you are trying to do in the second example isn't possible. PHP is executing, including the writing of that line of JavaScript (to the file), and then JavaScript executes, but of course not in that text file.

Your two choices are to find a different way to get the timezone strictly in PHP, or else to get it with JavaScript and then use AJAX to trigger a later run of PHP, i.e. after JavaScript has run.

EDIT

Your JavaScript will fetch the timezone as before. Then it will send that to a separate file that outputs it:

var url = '..'; // url of a php file that JUST processes the file write
$.ajax({
  type: "POST",
  url: url,
  data: {
        'timezoneToPrint' : timezone
    }
});

And in your other PHP file, which you have just called, you can now print it to a file

if($_POST['timezoneToPrint']){
   // ..write the file here, the timezone is in $_POST['timezoneToPrint']
}
tmdesigned
  • 2,098
  • 2
  • 12
  • 20
  • Yes the script is working great and echo the right timezone, i just need also this reference in a .txt file – Andrea Turco Feb 01 '20 at 15:08
  • actually i don't have any idea how to complete the writing of the .txt file with timezone in it with ajax.. mm – Andrea Turco Feb 01 '20 at 15:10
  • I've added a bit above that should point you in the right direction. Basically since PHP always runs first, what you have to do is use JavaScript to trigger a **second** file processing, so that when PHP runs *that* time it has the data JavaScript prepared. – tmdesigned Feb 01 '20 at 15:15
  • Your Solutions WORKS GREAT. Thank you my friend ! – Andrea Turco Feb 01 '20 at 15:32