我正在使用它计算我的网站的点击次数:
$counter_name = "counter.txt";
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
我想问一下,当两个或更多访问者同时打开页面时是否会出现问题?如果是,如何计算所有点击次数?
当(例如)100个用户在同一时间打开页面时,该文件不会被其中一个锁定?
非常感谢!
答案 0 :(得分:0)
这可能会对您有所帮助:
$filename = "counter.txt";
$number = file_get_contents($filename);
$file = fopen($filename, 'a');
if (flock($file, LOCK_EX)) {
ftruncate($file, 0);
fwrite($file, $number+1);
flock($file, LOCK_UN);
}
fclose($file);