Lock state file while processing request

This commit is contained in:
2026-08-03 20:54:52 +02:00
parent 553cbf4eae
commit 16e409727b
+17 -9
View File
@@ -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);