【发布时间】:2011-07-12 03:06:50
【问题描述】:
此脚本在 100,000 后重置。我需要更改哪些内容以防止重置并继续计数?
<?php
$filename1 = 'content/general_site_data/total_site_page_loads.txt';
if (file_exists($filename1)) {
$fh = fopen("content/general_site_data/total_site_page_loads.txt", "a+");
if($fh==false)
die("unable to create file");
$filec = 'content/general_site_data/total_site_page_loads.txt';
if (!is_writable($filec))
die('not writable');
$total_site_page_loads = trim(file_get_contents($filec)) + 1;
fwrite(fopen($filec, 'w'), $total_site_page_loads);
echo '------------------------------<br />
Site Wide Page Views: '.$total_site_page_loads.'<br />';
} else {
$fh = fopen($filename1, "a");
$total_site_page_loads = trim(file_get_contents($filename1)) + 1;
fwrite($fh, $total_site_page_loads);
fclose($fh);
echo '------------------------------<br />
Site Wide Page Views: '.$total_site_page_loads.'<br />';
}
?>
【问题讨论】:
-
这段代码中没有任何内容会导致重置。
-
你能举个例子说明当接近 100,000 时计数文件如何变化?
-
这里没有文件锁定,
w模式下第二次打开执行截断。经典的比赛条件,因此可能会重置。答案即将到来。 -
@Charles 但“w”访问似乎仅在文件不存在时才运行
-
@Pekka,事实证明,在执行完代码之后,else 块实际上甚至不应该触发——初始打开处于追加或创建模式,因此文件存在检查不应该除非打开也失败,否则失败,这将导致脚本死机。我已经用更安全的代码更新了我的答案。 (我想这就是我长期使用平面文件数据库所得到的。可怕的回忆......)
标签: php hitcounter