如何防止此计数器重置为100,000?

mob*_*lus 1 php hitcounter

此脚本在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 />';
}
?>
Run Code Online (Sandbox Code Playgroud)

Cha*_*les 5

您的代码可能正在遭受竞争条件的影响.

在中途,您以w模式重新打开文件,将文件截断为零长度.如果脚本的另一个副本打开并尝试在文件被截断但读取之前读取该文件,则计数器将重置为零.

这是您的代码的更新版本:

    $filename = 'content/general_site_data/total_site_page_loads.txt';
// Open our file in append-or-create mode.
    $fh = fopen($filename, "a+");
    if(!$fh)
        die("unable to create file");
// Before doing anything else, get an exclusive lock on the file.
// This will prevent anybody else from reading or writing to it.
    flock($fh, LOCK_EX);
// Place the pointer at the start of the file.
    fseek($fh, 0);
// Read one line from the file, then increment the number.
// There should only ever be one line.
    $total_site_page_loads = 1 + intval(trim(fgets($fh)));
// Now we can reset the pointer again, and truncate the file to zero length.
    fseek($fh, 0);
    ftruncate($fh, 0);
// Now we can write out our line.
    fwrite($fh, $total_site_page_loads . "\n");
// And we're done.  Closing the file will also release the lock.
    fclose($fh);
    echo '------------------------------',
         '<br />Site Wide Page Views: ',
         $total_site_page_loads,
         '<br />';
Run Code Online (Sandbox Code Playgroud)

由于初始打开处于追加或创建模式,因此您无需处理文件不存在的情况,除非初始打开失败.

随着文件锁定在适当位置,此代码应从未重置文件中的柜台,无论有多少并发请求有.(当然,除非你碰巧还有其他代码写入文件.)

  • 干得好.出于好奇,锁定到位后会发生什么 - 并发脚本会等待还是跳过? (3认同)
  • LOCK_EX是一个阻塞操作,所以脚本会等待片刻,直到事情被释放.如果锁的所有者退出但未释放它,则正确的锁实现将释放锁.实际上,这取决于操作系统和文件系统.这里有各种各样的边缘情况问题,包括操作系统耗尽文件锁(严重)和古老的NFS版本,如果文件系统是NFS挂载,那就搞砸了,尽管这对于真正的旧Solaris版本来说似乎是一个问题.真正可怕的网络主机,通常由电信公司运营.我有时讨厌我的旧工作. (3认同)