Location: PHPKode > scripts > giCounter > gicounter/giCounter.php
<?php

class giCounter
{

    var $page;
    
    var $file = "counter.dat";
    
    define('FILE_APPEND', 1);
    
    
    /**
     * Just sets the page
     *
     * @param string $page the page name
     */    
    function set_page($page)
    {
        $this->page = trim($page);
    }
    
    /**
     * And this one sets the file name
     *
     * @param string $file the counter file
     */  
    function set_file($file)
    {
        $this->file = trim($file);
    }
    


	/**

	 * write_file() is a file_put_contents(9 clone for PHP versions < 5.
	 * It is identical to calling fopen(), fwrite() and fclose() successively.

	 *

	 * @param string $filename the file name where to write the data

	 * @param mixed $data the data to write. Can be either a string, an array or a stream resource.

	 * @param int $flag flags can take FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX (acquire an exclusive lock), however the FILE_USE_INCLUDE_PATH option should be used with caution.

	 * @return int returns the amount of bytes that were written to the file.

	 */


    function write_file($filename, $data, $flag = false)

    {

		$mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';


		$f = @fopen($filename, $mode);


		if ($f === false) return 0;

		else {

			if (is_array($data)) $data = implode($data);


			$bytes_written = fwrite($f, $data);

			fclose($f);


			return $bytes_written;

		}


	}

    /**
     * Actually makes the work. Passing the reset mode (0) or the counter mode (1)
     * you set what the function has to do.
     *
     * @param int $MODE Use 0 to reset, 1 to get the counter
     * @return int the counter
     */
    function process($MODE)
    {
        if (!file_exists($this->file))
            fopen($this->file, "w");
                    
        $file = unserialize(file_get_contents($this->file));
        
        $counter = $file[$this->page];
        
        if ($MODE)
            $counter ++;
        else
            $counter = 0;
        
        $file[$this->page] = $counter;
        
        $this->write_file($this->file, serialize($file));
        
        return $counter;    
    }
    
    /**
     * Ask the process() function for the counter. Counter mode = 1
     *
     * @see process()
     * @return int the counter
     */
    function get_counter()
    {        
        return $this->process(1);
    }
    
    /**
     * Resets the counter by passing 0 to the process() function.
     * 
     * @see process()
     * @return int the counter
     */
    function reset()
    {
        return $this->process(0);
    }
    
}

?> 
Return current item: giCounter