javascriptphpechofwritefputs

php echo a javascript variable to file.txt


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?


Solution

  • 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']
    }