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中soap用法示例【SoapServer服务端与SoapClient客户端编写】

本文实例讲述了PHP中soap用法。分享给大家供大家参考,具体如下: 一、首先要设置服务器环境 修改php.ini 得添加extension=php_soap.dll (加载soap 内...

PHP中strtotime函数使用方法详解

在PHP中有个叫做strtotime的函数。strtotime 实现功能:获取某个日期的时间戳,或获取某个时间的时间戳。strtotime 将任何英文文本的日期时间描述解析为Unix时间...

php更新cookie内容的详细方法

cookie 是由服务器发送到浏览器的变量。cookie 通常是服务器嵌入到用户计算机中的小文本文件。 每当计算机通过浏览器请求一个页面,就会发送这个 cookie。 (推荐学习:PHP...

CentOS安装php v8js教程

CentOS release 5.11 (Final),CentOS release 6.6 (Final) x64测试通过。 gcc版本,glibc版本,libstdc++.so.6版...

处理单名多值表单的详解

就使用一个简单的可多选的select:复制代码 代码如下:<?phpecho<<<EOT<form action="" method=get>&nbs...