我通过将当前计数存储在文件中来制作一个简单的页面加载计数器.这就是我想要这样做的方式:
>锁定文件(flock)
>读取当前计数(fread)
>增加它()
>写新计数(fwrite)
>解锁文件/关闭它(flock / fclose)
这可以在不失锁的情况下完成吗?
如上所述,你可以使用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);