当前位置: 首页 > 图文教程 > 网络编程 > PHP > php 多线程上下文中安全写文件实现代码

PHP
PHP中上传大体积文件时需要的设置
用PHP生成PDF文件 with FPDF
在同一窗体中使用PHP来处理多个提交任务
PHP经验交流:php访问access的方法
PHP实用手册:PHP常用正则表达式收集
也用PHP来实现网页静态发布的两种方法
PHP使用zlib扩展实现页面GZIP压缩输出
PHP的语言层面的优化以及代码优化技巧
PHP实例:上传多个图片并校验的代码
用php+odbc+access数据库来操作函数
用PHP来实现页面GZIP的压缩输出教程
PHP进阶技巧:php用流方式制作缩略图
使用php 5时MySQL返回乱码的解决办法
新手如何使用PHP来创建RSS的阅读器
PHP实用:用PHP来实现图片的简单上传
利用php和js来轻松实现页面数据的刷新
在PHP中使用随机数的三个步骤详细代码
PHP进阶技巧:如何避免表单的重复提交
PHP技术进阶 PHP SOCKET 技术研究
PHP技术进阶:php用流方式制作缩略图

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 56 ::
收藏到网摘: n/a

提供一个php多线程上下文中安全写文件的实现方法。这个实现没有使用php 的file lock机制,使用的是临时文件机制。多线程中的各个线程都是对各自(每个线程独占一个)的临时文件写,然后再同步到原文件中。
复制代码 代码如下:

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