note 82934 added to function.file-put-contents
| From: | Anonymous at osu1 dot php dot net | Date: | Fri, 02 May 2008 18:06:15 +0000 |
| Subject: | note 82934 added to function.file-put-contents | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-138999@lists.php.net to get a copy of this message | ||
(someone delete my previous post, please - it had two bugs!)
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;
}
?>
----
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/82934
Del: integrated -- https://master.php.net/note/delete/82934/integrated
Del: useless -- https://master.php.net/note/delete/82934/useless
Del: bad code -- https://master.php.net/note/delete/82934/bad+code
Del: spam -- https://master.php.net/note/delete/82934/spam
Del: non-english -- https://master.php.net/note/delete/82934/non-english
Del: in docs -- https://master.php.net/note/delete/82934/in+docs
Del: other reasons-- https://master.php.net/note/delete/82934
Reject -- https://master.php.net/note/reject/82934
Search -- https://master.php.net/manage/user-notes.php