Counter in php script

fbsd_user fbsd_user at
Sun Feb 29 07:01:25 PST 2004

Thanks, a really great reply.
Have some questions about the fine details.

The counter file is an single line with any size numeric
field starting in position 1?
Like this, right?

Does the file have to be an  .txt  file?

What happens if the counter file is in use and locked?
Does the second request pause until file is free?

If the counter file has no path prefix, then it's looked for
in the same location as the script, right?
$counter_file = 'counter.php'

-----Original Message-----
From: owner-freebsd-questions at
[mailto:owner-freebsd-questions at]On Behalf Of Peter
Sent: Sunday, February 29, 2004 9:09 AM
To: fbsd_user at
Cc: freebsd-questions at FreeBSD. ORG
Subject: Re: Counter in php script

fbsd_user wrote:

>Need to set the initial value for an counter and save it, then
>bump the saved value by one every time the php script is executed.
>This must be a very basic function, but not being an php
>script coder my self this is all new to my.
>Can anyone provide sample code I can use to do this?
 From a user contribution to the php manual at

- edit to suit and use at your own risk.


|$counter_file = '/tmp/counter.txt';
ignore_user_abort(true);    ## prevent refresh from aborting file
operations and hosing file
if (file_exists($counter_file)) {
   $fh = fopen($counter_file, 'r+');
   while(1) {
     if (flock($fh, LOCK_EX)) {
         #$buffer = chop(fgets($fh, 2));
         $buffer = chop(fread($fh, filesize($counter_file)));
         fwrite($fh, $buffer);
         ftruncate($fh, ftell($fh));
         flock($fh, LOCK_UN);
else {
   $fh = fopen($counter_file, 'w+');
   fwrite($fh, "1");

print "Count is $buffer";


freebsd-questions at mailing list
To unsubscribe, send any mail to
"freebsd-questions-unsubscribe at"

More information about the freebsd-questions mailing list