Copy Code code as follows:
<?php
/**
* @usage: Used to offer safe file write operation in multiple threads context, arbitory file type
* @author: Rocky Zhang
* @time: Nov 11 2009
* @demo [0]: $handler = Mfopen ($file, ' A + ');
* Mfwrite ($handler, $STR);
*/
function Mfopen ($file, $mode = ' w+ ') {
$tempfile = Generatetempfile ('./tempdir ', $file);
Preg_match ('/b/i ', $mode) | | ($mode. = ' B '); ' B ' is recommended
if (Preg_match ('/\w|a/i ', $mode) &&!is_writable ($file)) {
Exit ("{$file} is not writable!");
}
$filemtime = $filemtime 2 = 0;
$tempdir = DirName ($tempfile);
Is_dir ($tempdir) | | mkdir ($tempdir, 0777);
do {//Do-while used to avoid modify in-a long time copy
Clearstatcache ();
$filemtime = Filemtime ($file);
Copy ($file, $tempfile);
$filemtime 2 = filemtime ($file);
while (($filemtime 2-$filemtime)!= 0);
if (! $handler = fopen ($tempfile, $mode)) {
Exit (' Fail on opening tempfile, write authentication are must on temporary dir! ');
}
Return Array (0=> $handler, 1=> $filemtime, 2=> $file, 3=> $tempfile, 4=> $mode);
}
I do the This function should be optimized further
Function Mfwrite (& $handler, $str = ') {
if (strlen ($STR) > 0) {
$num = fwrite ($handler [0], $STR);
Fflush ($handler [0]);
}
Clearstatcache ();
$mtime = Filemtime ($handler [2]);
if ($mtime = = $handler [1]) {//compare between source file and temporary file
if ($num && $num > 0) {//temporary file has been updated, copy to source file
Copy ($handler [3], $handler [2]) | | Exit
$handler [1] = Filemtime ($handler [3]);
Touch ($handler [2], $handler [1], $handler [1]);
}
else {//source file has been modified, load source file to temporary file
Copy ($handler [2], $handler [3]) | | Exit
Touch ($handler [3], $mtime, $mtime);
$handler [1] = $mtime;
}
}
function Generatetempfile ($tempdir = ' tempdir ', $file) {
$rand = MD5 (Microtime ());
Return "{$tempdir}/{$rand}_". $file;
}
?>