Guy Fieri Guy Fieri - 3 months ago 21
PHP Question

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 ).'"' ?>];


This PHP code is at the top of my script section in head. The seats.txt file is full of zeroes initially to represent vacant seats on a flight and through other functions, the seats will fill up (represented by 1s). I can get the 1s to write to the file but as soon as I reload the page, the if-statement seems to execute regardless of its condition being false and resets everything back to zero.

Answer

The reason is due to this w mode

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

So every time your file gets blank

Use a or a+ if you want to append at the right of file or r+ if you want to right from starting

Comments