note 82796 added to function.file-put-contents

From: Date: Fri, 25 Apr 2008 21:35:34 +0000
Subject: note 82796 added to function.file-put-contents
Groups: php.notes 
Request: Send a blank email to php-notes+get-138785@lists.php.net to get a copy of this message
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($_tmp_file, '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($params['filename'], FILE_PUT_CONTENTS_ATOMIC_MODE); return true; } ?> ---- Server IP: 87.54.44.10 Probable Submitter: 87.58.113.149 ---- Manual Page -- http://www.php.net/manual/en/function.file-put-contents.php Edit -- https://master.php.net/note/edit/82796 Del: integrated -- https://master.php.net/note/delete/82796/integrated Del: useless -- https://master.php.net/note/delete/82796/useless Del: bad code -- https://master.php.net/note/delete/82796/bad+code Del: spam -- https://master.php.net/note/delete/82796/spam Del: non-english -- https://master.php.net/note/delete/82796/non-english Del: in docs -- https://master.php.net/note/delete/82796/in+docs Del: other reasons-- https://master.php.net/note/delete/82796 Reject -- https://master.php.net/note/reject/82796 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138785) next »