Simple Flat-File Page Counter
Posted: Fri May 25, 2007 7:29 am
Code: Select all
<?php
/*
* SMCounter - Class to generate a flat file based counter
* Distributed freely -- use and redistribute as you wish
* Written: 5-25-2007
*/
class SMCounter
{
/*
* Value of our current counter
* int $current_count
*/
var $current_count;
/*
* Filename of the counter.txt file
* str $filename
*/
var $filename = 'SMCounter.txt';
/*
* gets the current counter and increments it by 1
*/
function get_count()
{
$this->current_count = (int) trim(file_get_contents($this->filename));
return $this->increment_count($this->filename);
}
/*
* writes the new incremented counter value
* and returns the new counter value
*/
function increment_count()
{
$new_count = $this->get_new_count();
$this->write_count($new_count);
return $new_count;
}
/*
* increments and returns the value of $this->current_count
*/
function get_new_count()
{
return $this->current_count + 1;
}
/*
* writes the $new_count to the $this->filename
* @param int $new_count
*/
function write_count($new_count)
{
$handle = fopen($this->filename, "w");
flock($handle, LOCK_EX);
fwrite($handle, $new_count);
flock($handle, LOCK_UN);
fclose($handle);
}
}
?>Code: Select all
<?php
$counter = new SMCounter();
echo $counter->get_count();