How to reset a persistent counter at a particular value?

和自甴很熟 提交于 2019-12-06 10:02:31
    if($current >= $reset) {
        // here is where you are setting the counter back to zero. comment out
        // these lines.
        //$new = '0';            
        //fwrite(fopen($filename4, 'w'), $new);                        
    }

If you simply want a counter that doesn't get reset, try:

$filename4 = "counter.txt";  

// Open our file in append-or-create mode.
$fh = fopen($filename4, "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 to get current count.
// There should only ever be one line.
$current = intval(trim(fgets($fh)));

// Increment
$new = $current++;

// 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, $new . "\n");

// And we're done.  Closing the file will also release the lock.
fclose($fh);

echo $new;                

The best way I can see to do this would be to open the file for reading with a lock other than exclusive. you can then perform your required checks and if the the count exceeds the $reset value, you can close the the file, open it again but this time with the exclusive lock for writing. Another way would simply not to use an exclusive lock. You could look into very good flatfile classes out there which have tested locking mechanisms.

file_put_contents is already atomic. There is no need for ten lines of file locking code.

<?php

    $fn = "$filename3.txt"; 

    $reset = 0;        // 0 is equivalent to "default"
    //$reset = 10000000;  

    $count = file_get_contents($fn);        
    $count = ($reset && ($count >= $reset)) ? (0) : ($count + 1);
    file_put_contents($fn, $count, LOCK_EX);

    echo $count;

No idea if this is any help, since your question is still opaque. I will not answer comments.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!