Permalink
Browse files

FSStorage: Write to temporary file and do a rename

To avoid a possible issue of serving a partly written file if the
Filesystem adapter is used with an existing image (inside a cache adapter
in this case), writing the file to a temporary file and then renaming that
file to its actually name would make sure we don't end up serving a partly
written file.

The rename() call is atomic, meaning that there is no time where the
contents inside the file we be partly available for anything reading the
file.
  • Loading branch information...
1 parent 830d4f1 commit 7f4782d878a853fac37105dbdc4c3aeafba9f08a @matslindh matslindh committed Nov 29, 2016
Showing with 4 additions and 1 deletion.
  1. +4 −1 src/Storage/Filesystem.php
@@ -75,13 +75,16 @@ public function store($user, $imageIdentifier, $imageData) {
$imagePath = $imageDir . '/' . $imageIdentifier;
- $bytesWritten = file_put_contents($imagePath, $imageData);
+ // write the file to .tmp, so we can do an atomic rename later to avoid possibly serving partly written files
+ $bytesWritten = file_put_contents($imagePath . '.tmp', $imageData);
// if write failed or 0 bytes were written (0 byte input == fail), or we wrote less than expected
if (!$bytesWritten || ($bytesWritten < strlen($imageData))) {
throw new StorageException('Failed writing file (disk full? zero bytes input?) to disk: ' . $imagePath, 507);
}
+ rename($imagePath . '.tmp', $imagePath);
+
return true;
}

0 comments on commit 7f4782d

Please sign in to comment.