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

相关文章

WordPress的主题编写中获取头部模板和底部模板

get_header()(获取头部) 引入主题的头部模板,默认会引入当前主题目录里的 header.php 文件。如果指定了一个名称,则引入当前主题目录的 header-{name}.p...

PHP 进度条函数的简单实例

PHP 进度条函数的简单实例

PHP 进度条函数的简单实例 其实进度条的做法很简单的。网上的一大堆,自己写了一个,哈哈,感觉看起来很有感觉。 实例代码: function ShowPercent($now,$to...

PHP QRCODE生成彩色二维码的方法

本文实例讲述了PHP QRCODE生成彩色二维码的方法。分享给大家供大家参考,具体如下: 这里重写了下PHPQRCODE,精简了部分代码,合并PNG GIF JPEG的输出. 参数说明:...

CMSPRESS 10行代码搞定 PHP无限级分类2

超级无限分类 使用简单 效率极高 核心代码10行不到 另外 求这个分类的不足,和更高效简单的无限分类方法 ^_^ 核心代码如下 class Tool { static pu...

php的优点总结 php有哪些优点

php有哪些优点? PHP优点: 1.入门快,有其它语言基础的程序员二周左右的时间就可以入门,一个月左右的时间基本上就可以开发简单的项目了。 2.开发成本低,PHP最经典的组合就是:Li...