1

此脚本在 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 />';
}
?>
4

2 回答 2

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 />';

因为初始打开处于追加或创建模式,所以您不需要处理文件不存在的情况,除非初始打开失败。

在文件锁定到位后,无论有多少并发请求,此代码都不应重置文件中的计数器(当然,除非您碰巧还有其他代码写入该文件。)

于 2011-03-09T18:11:13.720 回答
1

我看不到任何重置会发生在哪里,但脚本的工作方式似乎很简单。也许尝试编辑total_site_page_loads.txt类似的东西99990并观察当你越过该文件时该文件会发生什么100000

于 2011-03-09T18:08:45.187 回答