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

rafi
Forum Newbie
Posts: 19
Joined: Wed Nov 24, 2004 9:36 am

Post by rafi »

oups..thats my code..sorry.. :oops: :D
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

Yeah, he was showing you how to put it in PHP tags
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