php 多线程上下文中安全写文件实现代码
2015-01-24信息快讯网
提供一个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;
}
?>
php中随机显示图片的函数代码
使用php shell命令合并图片的代码
php whois查询API制作方法
PHP字符编码问题之GB2312 VS UTF-8解决方法
PHP读取网页文件内容的实现代码(fopen,curl等)
批量获取memcache值并按key的顺序返回的实现代码
php中通过虚代理实现延迟加载的实现代码
php获取后台Job管理的实现代码
php下通过curl抓取yahoo boss 搜索结果的实现代码
php统计文件大小,以GB、MB、KB、B输出
PHP文件上传原理简单分析
PHP获取文件绝对路径的代码(上一级目录)
PHP文件打开、关闭、写入的判断与执行代码
PHP多线程抓取网页实现代码
PHP类的使用 实例代码讲解
PHP 获取目录下的图片并随机显示的代码
phpMyAdmin链接MySql错误 个人解决方案
php 需要掌握的东西 不做浮躁的人
php 文章采集正则代码
PHP array_push 数组函数
在PHP中检查PHP文件是否有语法错误的方法
c#中的实现php中的preg_replace
php 来访国内外IP判断代码并实现页面跳转
php jquery 实现新闻标签分类与无刷新分页
将文件夹压缩成zip文件的php代码
php实现的仿阿里巴巴实现同类产品翻页
phpmyadmin导入(import)文件限制的解决办法
php5 图片验证码实现代码
PHP 读取文件内容代码(txt,js等)
PHPMyadmin 配置文件详解(配置)