一个PHP简易访问计数

source_php

嘛,受朋友所托写的,不是什么大不了的东西,贴上来就当给初学者参考吧
只有计数功能,利用session防止重复计数

注意只能运行在PHP5+上

代码见页内:

/**
 *  ezcounter
 *  http://vifix.cn
 *  MIT Lisence
 */
 
class ezcounter{
 
	const display_only = 1;
	const display_and_count = 0;
 
	private $file;
	private $hits;
 
	// 构造函数
	public function __construct($name = 'ezcounter'){
 
		// 存放计数的文件
		$this->file =  dirname(__FILE__) . "/$name.txt";
 
		// 判断文件是否存在,不存在则创建
		if(file_exists($this->file))
		{
			$this->hits = file_get_contents($this->file);
		}
		else
		{
			file_put_contents($this->file, "1");
			$this->hits = 1;
		}
	}
 
	// 获取计数
	public function gethits($flag = self::display_and_count){
		switch($flag)
		{
			case self::display_and_count:
				@session_start();
				if(!$_SESSION['ezcounter'])
				{
					$this->hits++;
					file_put_contents($this->file, $this->hits);
					$_SESSION['ezcounter'] = true;
				}
				return $this->hits;
				break;
			case self::display_only:
				return $this->hits;
				break;
		}
	}
 
	// 重定向计数
	public function redirect($url){
		@session_start();
		if(!$_SESSION['ezcounter'])
		{
			$this->hits++;
			file_put_contents($this->file, $this->hits);
			$_SESSION['ezcounter'] = true;
		}
		header("Location: $url");
	}
 
}

用法1,只是显示访问计数

require_once("ezcounter.php");
 
$counter = new ezcounter();
echo $counter->gethits(ezcounter::display_and_count);

用法2,转发计数(比如可以用于下载计数)

//download.php
require_once("ezcounter.php");
 
$counter = new ezcounter('another_file_name');
$counter->redirect('/target');
//view.php
require_once("ezcounter.php");
 
$counter = new ezcounter('another_file_name');
echo "<a href="download.php">" . $counter->gethits(ezcounter::display_only) . "</a>";

3 Responses

Leave a Comment

(Necessary)

(Necessary, will not be published)

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.