<?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
");
}
}
$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.
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
I am not sure whether I understand you correctly, but I think you only want to write the file if it does not exist:
<?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
");
}
fclose($myFile);
}
$seatsArray = file("seats.txt", FILE_IGNORE_NEW_LINES);
?>
var array = [<?php echo '"'.implode('","', $seatsArray ).'"' ?>];
Additionally, I would recommend putting the filename into a constant, which reduces the risk of typos (so PHP will complain, if it encounters an undefined constant in case of a typo).