note 82796 deleted from function.file-put-contents by danbrown
| From: | danbrown@php.net | Date: | Sat, 12 Jul 2008 15:42:31 +0000 |
| Subject: | note 82796 deleted from function.file-put-contents by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-141433@lists.php.net to get a copy of this message | ||
Note Submitter: rasmus at mindplay dot dk
----
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;
}
?>