======================================= PHP Safe File Reading & Writing ======================================= Always use locks when working with files or use a simple strategy with superior atomic renaming. ======================================= PHP Writing --------------------------------------- function safewrite($filepath, $data) { $dir = dirname($filepath); $tempfile = tempnam($dir, 'atomic_'); if ($tempfile === false) return false; if (file_put_contents($tempfile, $data, LOCK_EX) === false) { @unlink($tempfile); return false; } if (@rename($tempfile, $filepath) === false) { @unlink($tempfile); return false; } return true; } ======================================= PHP Reading --------------------------------------- function saferead($filepath) { if (!file_exists($filepath)) { return false; } $context = stream_context_create([ 'file' => ['lock' => LOCK_EX] ]); return file_get_contents($filepath, false, $context); } ======================================= Done =======================================