PHP并发下安全的文件读写方式

可道云是一款非常强大的私有云和在线文档管理系统,源码之中有很多借鉴的方法

安全读取文件,避免并发下读取数据为空

function file_read_safe($file,$timeout = 0.1){
	clearstatcache();
	if(!$file || !file_exists($file)) return false;

	$start_time = microtime(true);
	$index = 0;
	do{
		clearstatcache();
		$index++;
		$file_size = filesize($file);
		$result = @file_get_contents($file);
		if( $result === false ||
			!file_exists($file) ||
			strlen($result) !== $file_size){
			usleep(round(rand(0,1000)*50));//0.01~10ms
		}else{
			return $result;
		}
	}while($index<=100 && (microtime(true)-$start_time) < $timeout );
	return false;
}

安全写入文件,避免并发下产生的影响

function file_wirte_safe($file,$buffer,$timeout=0.1){
	clearstatcache();
	$fileTemp = $file.'.'.time().rand_string(5);
	if(!$fp = fopen($fileTemp, "w")){
		@unlink($fileTemp);
		return false;
	}
	fwrite($fp, $buffer);
	fclose($fp);
	
	$file_lock = $file.'.lock';
	$start_time = microtime(true);
	$index = 0;
	do{
		clearstatcache();
		$index++;
		if(!file_exists($file_lock)){
			@rename($file,$file_lock);
		}
		$result = @rename($fileTemp,$file);
		if( $result === false || file_exists($fileTemp)){
			usleep(round(rand(0,1000)*10));//0.01~10ms
		}else{
			@unlink($file_lock);
			return true;
		}
	}while($index<=100 && (microtime(true)-$start_time)<$timeout );
	return false;
}

原创文章,作者:witersen,如若转载,请注明出处:https://www.witersen.com

(0)
witersen的头像witersen
上一篇 2021年1月3日 下午2:23
下一篇 2021年1月18日 下午2:13

相关推荐

  • Centos8安装PHP

    安装好虚拟机后,可以进行PHP的安装。 一:安装Apache 1.安装Apache:执行命令yum install httpd 2.配置ServerName:执行命令vi /etc…

    2020年12月26日
    2.2K0

发表回复

登录后才能评论