Counter in php script
Peter Risdon
peter at circlesquared.com
Sun Feb 29 06:08:40 PST 2004
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
http://www.php.net/manual/en/function.fopen.php
- edit to suit and use at your own risk.
PWR.
|$counter_file = '/tmp/counter.txt';
clearstatcache();
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)));
$buffer++;
rewind($fh);
fwrite($fh, $buffer);
fflush($fh);
ftruncate($fh, ftell($fh));
flock($fh, LOCK_UN);
break;
}
}
}
else {
$fh = fopen($counter_file, 'w+');
fwrite($fh, "1");
$buffer="1";
}
fclose($fh);
print "Count is $buffer";
?>|
More information about the freebsd-questions
mailing list