PHP Counter
Moderator: General Moderators
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
I wrote this class recently, but never got around to adding file locking. I would love it if some smart programmer could add the file locking part. The one good thing about this code is that it is compatible with Perl::Counter so can be used with Perl scripts and share the counter file.
Code: Select all
class PerlCounter {
var $header = "#COUNTER-1.0\n";
function increment($filename) {
$offset = strlen($this->header);
$counter = 0;
$fp = fopen($filename, 'r+');
if ($fp) {
$contents = fread($fp, filesize($filename));
if ($contents) {
$counter = intval(trim(substr($contents, $offset)));
}
++$counter;
$contents = "{$this->header}$counter\n";
rewind($fp);
fwrite($fp, $contents);
ftruncate($fp, strlen($contents));
fclose($fp);
}
return $counter;
}
} // end class