php 多线程上下文中安全写文件实现代码

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

<?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;
}
?>

相关文章

PHP 冒泡排序 二分查找 顺序查找 二维数组排序算法函数的详解

数据结构很重要,算法+数据结构+文档=程序使用PHP描述冒泡排序算法,对象可以是一个数组复制代码 代码如下://冒泡排序(数组排序)function bubble_sort($array...

利用PHP扩展vld查看PHP opcode操作步骤

首先下载最新版vld扩展: 复制代码 代码如下: ~/public_html/php-5.3.13/ext> wget http://pecl.php.net/get/vld-0....

PHP中return 和 exit 、break和contiue 区别与用法

先说一下exit函数的用法。 作用: 输出一则消息并且终止当前脚本。 如果一段文本中包括多个以 结束的脚本,则exit退出当前所在脚本。 比如一篇php文本包括一下代码,则输出为worl...

PHP调试的强悍利器之PHPDBG

PHPDBG是一个PHP的SAPI模块,可以在不用修改代码和不影响性能的情况下控制PHP的运行环境。 PHPDBG的目标是成为一个轻量级、强大、易用的PHP调试平台。可以在PHP5.4和...

php自定义函数call_user_func和call_user_func_array详解

call_user_func函数类似于一种特别的调用函数的方法,使用方法如下: 复制代码 代码如下: function a($b,$c) { echo $b; echo $c; } ca...