From 5290e978bdb8cdd66290d1344d57f088227db31a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 13 Jan 2021 14:01:18 +0100 Subject: [PATCH] [HttpFoundation] use atomic writes in MockFileSessionStorage --- .../Storage/MockFileSessionStorage.php | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php index c96b3cd9dc..380f656b08 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/MockFileSessionStorage.php @@ -103,7 +103,10 @@ class MockFileSessionStorage extends MockArraySessionStorage try { if ($data) { - file_put_contents($this->getFilePath(), serialize($data)); + $path = $this->getFilePath(); + $tmp = $path.bin2hex(random_bytes(6)); + file_put_contents($tmp, serialize($data)); + rename($tmp, $path); } else { $this->destroy(); } @@ -123,8 +126,11 @@ class MockFileSessionStorage extends MockArraySessionStorage */ private function destroy(): void { - if (is_file($this->getFilePath())) { + set_error_handler(static function () {}); + try { unlink($this->getFilePath()); + } finally { + restore_error_handler(); } } @@ -141,8 +147,14 @@ class MockFileSessionStorage extends MockArraySessionStorage */ private function read(): void { - $filePath = $this->getFilePath(); - $this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : []; + set_error_handler(static function () {}); + try { + $data = file_get_contents($this->getFilePath()); + } finally { + restore_error_handler(); + } + + $this->data = $data ? unserialize($data) : []; $this->loadSession(); }