note 82934 deleted from function.file-put-contents by googleguy

From: Date: Mon, 27 Jun 2016 16:18:06 +0000
Subject: note 82934 deleted from function.file-put-contents by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-205823@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- file_put_contents() will cause concurrency problems - that is, it doesn't write files atomically (in a single operation), which sometimes means that one php script will be able to, for example, read a file before another script is done writing that file completely. The following function was derived from a function in Smarty (http://smarty.php.net) which uses rename() to replace the file - rename() is atomic on Linux. On Windows, rename() is not currently atomic, but should be in the next release. Until then, this function, if used on Windows, will fall back on unlink() and rename(), which is still not atomic... <?php define("FILE_PUT_CONTENTS_ATOMIC_TEMP", dirname(__FILE__)."/cache"); define("FILE_PUT_CONTENTS_ATOMIC_MODE", 0777); function file_put_contents_atomic($filename, $content) { $temp = tempnam(FILE_PUT_CONTENTS_ATOMIC_TEMP, 'temp'); if (!($f = @fopen($temp, 'wb'))) { $temp = FILE_PUT_CONTENTS_ATOMIC_TEMP . DIRECTORY_SEPARATOR . uniqid('temp'); if (!($f = @fopen($temp, 'wb'))) { trigger_error("file_put_contents_atomic() : error writing temporary file '$temp'", E_USER_WARNING); return false; } } fwrite($f, $content); fclose($f); if (!@rename($temp, $filename)) { @unlink($filename); @rename($temp, $filename); } @chmod($filename, FILE_PUT_CONTENTS_ATOMIC_MODE); return true; } ?>

« previous php.notes (#205823) next »