php多线程上下文中安全写文件实现代码
2023-06-13 09:14:15 时间
<?php
/**
*@usage:usedtooffersafefilewriteoperationinmultiplethreadscontext,arbitoryfiletype
*@author:RockyZhang
*@time:Nov.112009
*@demo[0]:$handler=mfopen($file,"a+");
*mfwrite($handler,$str);
*/
functionmfopen($file,$mode="w+"){
$tempfile=generateTempfile("./tempdir",$file);
preg_match("/b/i",$mode)||($mode.="b");//"b"isrecommended
if(preg_match("/\w|a/i",$mode)&&!is_writable($file)){
exit("{$file}isnotwritable!");
}
$filemtime=$filemtime2=0;
$tempdir=dirname($tempfile);
is_dir($tempdir)||mkdir($tempdir,0777);
do{//do-whileusedtoavoidmodifyinalongtimecopy
clearstatcache();
$filemtime=filemtime($file);
copy($file,$tempfile);
$filemtime2=filemtime($file);
}while(($filemtime2-$filemtime)!=0);
if(!$handler=fopen($tempfile,$mode)){
exit("Failonopeningtempfile,writeauthenticationismustontemporarydir!");
}
returnarray(0=>$handler,1=>$filemtime,2=>$file,3=>$tempfile,4=>$mode);
}
//Idothinkthatthisfunctionshouldbeoptimizedfurther
functionmfwrite(&$handler,$str=""){
if(strlen($str)>0){
$num=fwrite($handler[0],$str);
fflush($handler[0]);
}
clearstatcache();
$mtime=filemtime($handler[2]);
if($mtime==$handler[1]){//comparebetweensourcefileandtemporaryfile
if($num&&$num>0){//temporaryfilehasbeenupdated,copytosourcefile
copy($handler[3],$handler[2])||exit;
$handler[1]=filemtime($handler[3]);
touch($handler[2],$handler[1],$handler[1]);
}
}else{//sourcefilehasbeenmodified,loadsourcefiletotemporaryfile
copy($handler[2],$handler[3])||exit;
touch($handler[3],$mtime,$mtime);
$handler[1]=$mtime;
}
}
functiongenerateTempfile($tempdir="tempdir",$file){
$rand=md5(microtime());
return"{$tempdir}/{$rand}_".$file;
}
?>
相关文章
- php格式怎么转换为pdf,PHP如何将将word文件转为pdf
- PHP文件包含漏洞攻防实战(allow_url_fopen、open_basedir)
- 宝塔新建php文件实现百度自动推送
- 最全的PHP后台管理系统源码「建议收藏」
- php案例:压缩一个文件
- PHP date():时间日期格式化
- Linux新建PHP文件的操作指南(linux新建php文件)
- 文件MySQL更新实现快速PHP文件升级(mysql更新php)
- 使用PHP连接Linux,轻松实现物联网设备管理。(php连接linux)
- PHP操作MySQL数据库的完整指南(php读写mysql)
- PHP实现在Linux系统中进行文件操作(php写linux文件)
- 使用PHP连接Oracle数据库(php连接oracle)
- PHP连接MS SQL服务器添加数据(php 添加mssql)
- PHP编写的MSSQL查询:实现可能性无限(php写mssql查询)
- Linux平台如何高效搜索PHP文件(linux搜索php)
- 在PHP中操作MSSQL数据库:事务处理技巧(php mssql 事务)
- 修改了一个很不错的php验证码(支持中文)
- PHP和Mysqlweb应用开发核心技术第1部分Php基础-1开始了解php
- php入门学习知识点六PHP文件的读写操作代码
- PHP中的生成XML文件的4种方法分享
- php判断上传的Excel文件中是否有图片及PHPExcel库认识
- PHP和.net中des加解密的实现方法
- PureFTPd+Mysql+PHP_Manager实现虚拟用户磁盘限额的配置方法
- php四种基础算法代码实例
- PHP中实现生成静态文件的方法缓解服务器压力
- PHP+jQuery注册模块的改进(二):邮箱激活
- php文件上传简单实现方法
- PHP针对常规模板引擎中与CSS/JSON冲突的解决方法