rosell-dk / webp-convert

Convert jpeg/png to webp with PHP (if at all possible)
MIT License
576 stars 101 forks source link

CreateDestinationFolderException: mkdir race condition #328

Open AlexeyKosov opened 2 years ago

AlexeyKosov commented 2 years ago

When a browser sends many requests for image conversion concurrently (e.g. an image gallery is loaded) and the destination directory does not exist, every request tries to create the directory, which ends up with CreateDestinationFolderException because of a race condition.

So instead of

if (! is_dir($dir) && ! mkdir($dir, 0777, true)) {
    throw new CreateDestinationFolderException();
}

the following should be used:

if (! is_dir($dir) && ! mkdir($dir, 0777, true) && ! is_dir($dir)) {
    throw new CreateDestinationFolderException();
}

(code is simplified)

More info about this issue:

https://www.google.com/search?q=php+mkdir+race+condition https://bugs.php.net/bug.php?id=35326 https://stackoverflow.com/questions/44322783/is-is-dir-unreliable-or-are-there-race-conditions-that-can-be-mitigated-here/57939677#57939677 https://app.bountysource.com/issues/49427500-mkdir-race-condition-enhancement https://github.com/symfony/symfony/issues/11626