simple-cache icon indicating copy to clipboard operation
simple-cache copied to clipboard

Driver for file backend is racy (because file_put_contents() is racy)

Open mikkorantalainen opened this issue 6 months ago • 0 comments

The PHP file_put_contents() is racy and this line of code will result in corrupted file if two processes try to write in parallel and readers may see partial file contents even if only one process is writing at a time:

https://github.com/terrylinooo/simple-cache/blob/b8560f9828164daff0560fe97ffd9b246e81ed8e/src/SimpleCache/Driver/File.php#L100

See https://github.com/php/php-src/issues/20108 for details. The correct way to write new files is to create new temporary file in the same directory with the target file, use file_put_contents() to write into temporary file and then rename() the file to target filename. This results in atomic behavior according to POSIX spec and all other implementations are racy (because POSIX doesn't provide other atomic file operations).

Also note that file_put_contents() can return zero vs false, but both are falsy, so it would be better to do if (false === file_put_contents... here. I think it's pretty safe to assume that even future PHP versions can never serialize anything to an empty string but comparing against false would be always safe option.

mikkorantalainen avatar Oct 22 '25 11:10 mikkorantalainen