php 多線程上下文中安全寫(xiě)文件實(shí)現(xiàn)代碼
更新時(shí)間:2009年12月28日 22:28:01 作者:
提供一個(gè)php多線程上下文中安全寫(xiě)文件的實(shí)現(xiàn)方法。這個(gè)實(shí)現(xiàn)沒(méi)有使用php 的file lock機(jī)制,使用的是臨時(shí)文件機(jī)制。多線程中的各個(gè)線程都是對(duì)各自(每個(gè)線程獨(dú)占一個(gè))的臨時(shí)文件寫(xiě),然后再同步到原文件中。
復(fù)制代碼 代碼如下:
<?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 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;
}
?>
您可能感興趣的文章:
相關(guān)文章
php實(shí)現(xiàn)的mongoDB單例模式操作類
這篇文章主要介紹了php實(shí)現(xiàn)的mongoDB單例模式操作類,結(jié)合實(shí)例形式分析了php基于單例模式操作MongoDB數(shù)據(jù)庫(kù)的數(shù)據(jù)庫(kù)封裝類相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-01-01PHP中使用addslashes函數(shù)轉(zhuǎn)義的安全性原理分析
這篇文章主要介紹了PHP中使用addslashes函數(shù)轉(zhuǎn)義的安全性原理分析,較為深入的分析了addslashes函數(shù)的用法及ecshop自定義函數(shù)addslashes_deep的不足之處,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-11-11PHP基于文件存儲(chǔ)實(shí)現(xiàn)緩存的方法
這篇文章主要介紹了PHP基于文件存儲(chǔ)實(shí)現(xiàn)緩存的方法,實(shí)例分析了smarty模板中php通過(guò)文件存儲(chǔ)來(lái)實(shí)現(xiàn)緩存的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07