← PHP / Laravel · Contents

PHP-044 / Advanced

Checking a file's existence before using it (TOCTOU)

A01:2021 Broken Access Control · CWE-367 TOCTOU Race Condition

Why is this a problem?

A symbolic link or similar mechanism can change the target between checking and use.

How to fix it

php
$fp = fopen($path, 'c+');  // Open, acquire flock, then perform the operation
flock($fp, LOCK_EX); ftruncate($fp, 0); fwrite($fp, $data); flock($fp, LOCK_UN); fclose($fp);

Further reading