PHP filesize if 语句即使在 false 时仍然执行

PHP filesize if-statement still executes even when false

<?php
$seatsArray = array();
$myFile = fopen("seats.txt", "w") or die("Unable to Open File!");
if(filesize("seats.txt") == 0) {
    for($x = 0; $x < 10; $x++) {
        fwrite($myFile, "0\n");
    }
}   
$seatsArray = file("seats.txt", FILE_IGNORE_NEW_LINES);
fclose($myFile);
?>

var array = [<?php echo '"'.implode('","', $seatsArray ).'"' ?>];

此 PHP 代码位于 head 中我的脚本部分的顶部。 seats.txt 文件最初全是零以表示航班上的空座位,通过其他函数,座位将被填满(用 1 表示)。我可以让 1s 写入文件,但是一旦我重新加载页面,if 语句似乎会执行,无论其条件是否为 false 并将所有内容重置为零。

原因是因为这个w mode

w- (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)

所以每次你的 file 得到 blank

如果你想appendfile的右边使用a或者a+或者如果你想从开始的右边[=]使用r+ 19=]

我不确定我是否理解正确,但我认为你只想在文件不存在时写入:

<?php
$seatsArray = array();
if(!file_exists("seats.txt") || filesize("seats.txt") == 0) {
    $myFile = fopen("seats.txt", "w") or die("Unable to Open File!");
    for($x = 0; $x < 10; $x++) {
        fwrite($myFile, "0\n");
    }
    fclose($myFile);
}   
$seatsArray = file("seats.txt", FILE_IGNORE_NEW_LINES);
?>

var array = [<?php echo '"'.implode('","', $seatsArray ).'"' ?>];

此外,我建议将文件名放入一个常量中,这样可以减少拼写错误的风险(所以 PHP 会抱怨,如果在拼写错误的情况下遇到未定义的常量)。