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中类型转换 ,常量,系统常量,魔术常量的详解

PHP中类型转换 ,常量,系统常量,魔术常量的详解 1.自动类型转换; 在运算和判断时,会进行自动类型转换; 1)其他类型转为bool,判断时转换; 1)整型转布尔型:0转fal...

PHP面向对象学习之parent::关键字

前言 最近在做THINKPHP开发项目中,用到了 parent:: 关键字,实际上 parent::关键字 是PHP中常要用到的一个功能,这不仅仅是在 THINKPHP 项目开发中,即使...

浅谈PHP正则表达式中修饰符/i, /is, /s, /isU

在学习PHP正则表达式修饰符之前先来理解下贪婪模式,前面在元字符中提到过"?"还有一个重要的作用,即"贪婪模式",什么是"贪婪模式"呢? PHP正则表达式贪婪模式: 比如我们要匹...

PHP封装cURL工具类与应用示例

本文实例讲述了PHP封装cURL工具类。分享给大家供大家参考,具体如下: CurlUtils工具类: <?php /** * cURL请求工具类 */ class...

PHP array操作10个小技巧分享

1、向array中添加元素 php是一个弱类型语言。因此不必象c语言那样为php array声明长度。向其中添加元素的过程也是声明和初始化的过程。 复制代码 代码如下: $capital...