😄

カウンター ファイル編 難しい版

2022/04/24に公開
<?php
//	...
error_reporting(E_ALL);

//	...
$file_name = 'count.txt';

//	...
if(!file_exists($file_name) ){
	echo "<p style='color:red;'>This file does not exist. ($file_name)</p>";
	return;
}

//	...
if(!is_writable($file_name) ){
	echo "<p style='color:red;'>Please add write permission to file. ($file_name)</p>";
	return;
}

//	...
if(!$file = fopen($file_name, 'r+') ){ // rb is Windows only read mode.
	echo "<p style='color:red;'>Failed to file open. ($file_name)</p>";
	return;
}

//	...
if(!flock($file, LOCK_EX) ){
	echo "<p style='color:red;'>Failed to file lock. ($file_name)</p>";
	FileClose($file);
	return;
}

//	...
$file_size = filesize($file_name);

//	...
if(!$file_size ){
	//	...
	$count = 0;
}else{
	//	...
	if(!$count = fread($file, $file_size) ){
		echo "<p style='color:red;'>Failed to file read. ($file_name)</p>";
		FileClose($file);
		return;
	}
}

//	...
$count++;

//	...
$count = (string)$count;

//	...
if(!rewind($file) ){
	echo "<p style='color:red;'>Failed to file rewind. ($file_name)</p>";
	FileClose($file);
	return;
}

//	...
if(!fwrite($file, $count) ){
	echo "<p style='color:red;'>Failed to file write. ($file_name)</p>";
}

//	...
FileClose($file);

//	...
echo $count;

/** File close process.
 *
 * @param resource
 */
function FileClose($file){
	//	...
	fflush($file);

	//	...
	flock($file, LOCK_UN);

	//	...
	fclose($file);
}

Discussion