web counters in files?

94 Views Asked by At

How do I store counters in php script without DB? Always was using DB but now I want simpler configuration... Using files seems to be problematic due to file locks. Let's say that there are many concurrent connections and I want to count number of script executions.

4

There are 4 best solutions below

4
On

You don't want to use a database and you don't want to use a file. I don't think it's possible to achieve that without using either of those.

2
On

You can increment a cached value in memory using something like memcache. It's probably the fastest solution to the concurrency problem.

Memcache or APC

Ofcourse you'll lose the data if memcache is cleared or restarted... file-persistence at some point is the only way.

0
On
<?php
$count_file = "counts.txt";
$counts = file($count_file);
$counts[0] ++;
$fp = fopen($count_file , "w");
fputs($fp , "$counts[0]");
fclose($fp);
echo $counts[0];
?>
4
On

I want to count number of script executions

Setup a directory you can write to. For each request create a new file with a random name.

You count the number of script executions by counting the number of files.

If you do the random with a low collision rate, you won't loose a count, or only very, very few. If you know the characteristics of the random source and hash function for the file-name, you can even statistically say how many counts you need to add.