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 に答える