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

yipeiwu_com6年前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开发中的页面跳转方法总结

页面跳转可能是由于用户单击链接、按钮等触发的,也可能是系统自动产生的。页面自动跳转在WEB开发中经常用到,而且根据需求可以采用不同的跳转方式,比如提示操作信息后延时跳转等, 本文总结了W...

php使用GD2绘制几何图形示例

php使用GD2绘制几何图形示例

本文实例讲述了php使用GD2绘制几何图形的方法。分享给大家供大家参考,具体如下: 使用GD2函数不仅可以绘制线条图形,而且可以绘制填充图形,如填充圆形,填充矩形等。下面对GD2中常用的...

PHP迅雷、快车、旋风下载专用链转换代码

复制一下代码,保存为cs.php即可,若要保存为其他名字,注意修改<form action=cs.php method=GET>这一行 复制代码 代码如下: <?php...

php源码分析之DZX1.5加密解密函数authcode用法

本文实例讲述了php源码分析之DZX1.5加密解密函数authcode用法。分享给大家供大家参考。具体分析如下: <?php $authkey = ''; /** *...

PHP 计算两个时间段之间交集的天数函数方法

函数:/**  * 计算两个时间段之间交集的天数  * @param $startDate1 开始日期1  * @...