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钩子与简单分发方式。分享给大家供大家参考,具体如下: //简单的钩子实现例子 class tool{ public static function main(...

PHP与C#分别格式化文件大小的代码

PHP 版: 复制代码 代码如下: function format($size) { $sizetext = array(" B", " KB", " MB", " GB", " TB"...

浅谈PHP的exec()函数无返回值排查方法(必看)

在安全imagemagic时 需要用到 exec很多服务器上安装失败 exec()执行外部命令失败,但没有任何错误信息。 exec执行某命令在命令行下没有问题,但是在php中就出错。这个...

解析crontab php自动运行的方法

crontab是linux自带的一个命令  使php自动运行的方法php自动运行有很多方法,这里分以下DZ以及一些通过系统完成的方法和直接触发运行驻留系统的方法。Discuz后...

基于PHP实现数据分页显示功能

本文实例为大家分享了数据分页显示功能的PHP实现代码,供大家参考,具体内容如下 实现代码: <!DOCTYPE html> <html> <head&g...