use tmp file for file writes, avoid race condition

This commit is contained in:
mohrt
2003-02-24 15:14:53 +00:00
parent 3e755114a3
commit f5f21995ef
2 changed files with 16 additions and 12 deletions

1
NEWS
View File

@@ -1,3 +1,4 @@
- use tmp file for file writes, avoid file lock race (Monte)
- handle embedded "$smarty.config.foo.tpl" correctly (Monte) - handle embedded "$smarty.config.foo.tpl" correctly (Monte)
- add $smarty.config.varname variable for accessing config vars (Paul - add $smarty.config.varname variable for accessing config vars (Paul
Lockaby, Monte) Lockaby, Monte)

View File

@@ -2041,22 +2041,25 @@ class Smarty
*/ */
function _write_file($filename, $contents, $create_dirs = false) function _write_file($filename, $contents, $create_dirs = false)
{ {
if ($create_dirs) $_dirname = dirname($filename);
$this->_create_dir_structure(dirname($filename));
if ($create_dirs) {
$this->_create_dir_structure($_dirname);
}
if (!($fd = @fopen($filename, 'w'))) { // write to tmp file, then rename it to avoid
$this->trigger_error("problem writing '$filename.'"); // file locking race condition
$_tmp_file = $_dirname . '/' . uniqid('');
if (!($fd = @fopen($_tmp_file, 'w'))) {
$this->trigger_error("problem writing temporary file '$_tmp_file'");
return false; return false;
} }
// flock doesn't seem to work on several windows platforms (98, NT4, NT5, ?), fwrite($fd, $contents);
// so we'll not use it at all in windows. fclose($fd);
rename($_tmp_file, $filename);
if ( strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || (flock($fd, LOCK_EX)) ) { chmod($filename, $this->_file_perms);
fwrite( $fd, $contents );
fclose($fd);
chmod($filename, $this->_file_perms);
}
return true; return true;
} }