PHP Counter

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

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
Post Reply