Copy codeThe Code is 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 = $ filemtime2 = 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 );
$ Filemtime2 = filemtime ($ file );
} While ($ filemtime2-$ filemtime )! = 0 );
If (! $ Handler = fopen ($ tempfile, $ mode )){
Exit ('fail on opening tempfile, write authentication is must on temporary dir! ');
}
Return array (0 => $ handler, 1 => $ filemtime, 2 => $ file, 3 => $ tempfile, 4 => $ mode );
}
// I do think that this function shocould 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;
}
?>