diff --git a/index.php b/index.php index 420ff84..9c90b42 100644 --- a/index.php +++ b/index.php @@ -28,16 +28,19 @@ if ($error_reporting) { ini_set('display_errors', 1); } -if (!file_exists($state_file)) { - $dirname = dirname($state_file); - if (!is_dir($dirname)) { - mkdir($dirname, 0777, true); - } - - file_put_contents($state_file, json_encode([ "lobbies" => []])); +$dirname = dirname($state_file); +if (!is_dir($dirname)) { + mkdir($dirname, 0777, true); } -$state = json_decode(file_get_contents($state_file), true); +$state_fp = fopen($state_file, "c+"); +flock($state_fp, LOCK_EX); + +$contents = stream_get_contents($state_fp); +$state = json_decode($contents, true); +if (empty($state)) { + $state = ["lobbies" => []]; +} $cutoff_timestamp = time() - $lobby_timeout_seconds; foreach (array_keys($state["lobbies"]) as $id) { @@ -148,4 +151,9 @@ else { echo json_encode(["status" => "OK"]); } -file_put_contents($state_file, json_encode($state, JSON_PRETTY_PRINT)); +ftruncate($state_fp, 0); +rewind($state_fp); +fwrite($state_fp, json_encode($state, JSON_PRETTY_PRINT)); +fflush($state_fp); +flock($state_fp, LOCK_UN); +fclose($state_fp);