Home > Net >  A trivial counter fails in PHP
A trivial counter fails in PHP

Time:10-05

I have a PHP script that updates a counter each time the page is retrieved. After creating the file in bash with

echo -n 0 > counterfile.txt

the PHP page looks like this:

<?php
$count = 'counterfile.txt';
file_put_contents($count,1 file_get_contents($count),LOCK_EX);
?>

The thing works fine, I see the counterfile.txt being updated, but once in a while the counter is reset, or at least sometimes today's counter value is less than yesterday's.

Why is this? Maybe some base-10 problem...? Maybe for some reason this is safer:

<?php
$count = 'counterfile.txt';
$n = file_get_contents($count);
file_put_contents($count,($n  ),LOCK_EX);
?>

CodePudding user response:

Make sure that the file_get_contents is successful (not returning false) before proceeding to write (otherwise the counter will be re-set as 1, which is not desirable)

Hence:

<?php
$count = 'counterfile.txt';
$var1=file_get_contents($count);

if ($var1!=false){
file_put_contents($count, (1 $var1) ,LOCK_EX);
}

?>

Alternatively, you may use a db approach (increment a field value by one each time)

  •  Tags:  
  • php
  • Related