我通过将当前计数存储在文件中来制作一个简单的页面加载计数器.这就是我想要这样做的方式:
这可以在不失锁的情况下完成吗?
据我了解,在不丢失锁定的情况下无法写入文件.我想出解决这个问题的唯一方法是使用"r +"模式编写一个字符,然后计算字符数.
Jam*_*cun 19
如上所述,你可以使用FLock.一个简单的例子是:
//Open the File Stream
$handle = fopen("file.txt","r+");
//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
$count = fread($handle, filesize("file.txt")); //Get Current Hit Count
$count = $count + 1; //Increment Hit Count by 1
ftruncate($handle, 0); //Truncate the file to 0
rewind($handle); //Set write pointer to beginning of file
fwrite($handle, $count); //Write the new Hit Count
flock($handle, LOCK_UN); //Unlock File
} else {
echo "Could not Lock File!";
}
//Close Stream
fclose($handle);
Run Code Online (Sandbox Code Playgroud)