Skip to content

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

@mikkorantalainen

Description

@mikkorantalainen

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:

if (file_put_contents($filePath, serialize($contents))) {

See php/php-src#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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions