Home > php教程 > PHP源码 > PHP浏览次数统计类visit.class.php配合文本缓存

PHP浏览次数统计类visit.class.php配合文本缓存

PHP中文网
Release: 2016-05-25 17:06:06
Original
1381 people have browsed it

使用示例:
$visit = app::loader('visit'); 
$article_id = 20722; 
$visit->count('article', $article);

<?php

class visit
{

public $expires = array();
public $tables = array();


public function __construct()
{
$this->expires[&#39;article&#39;] = 10;
$this->tables[&#39;article&#39;] = &#39;pcb_article&#39;;

$this->expires[&#39;forum&#39;] = 9;
$this->tables[&#39;forum&#39;] = &#39;pcb_forum&#39;;

$this->expires[&#39;blog&#39;] = 8;
$this->tables[&#39;blog&#39;] = &#39;pcb_blog&#39;;
}



public function count($channel, $id)
{
$path = $this->get_cache_path($channel);

$this->update($path, $channel, $id);
}


private function get_cache_expires($channel)
{
$expires = isset($this->expires[$channel]) ? $this->expires[$channel] : 10;
return $expires;
}

private function get_cache_path($channel)
{
$time = time();
$minute = date(&#39;H&#39;, $time) * 60 + date(&#39;i&#39;, $time);
$expires = $this->get_cache_expires($channel);

$path = SYS_PATH ."/data/cache/visit/{$channel}". ceil($minute / $expires) .".txt";
return $path;
}


private function update($path, $channel, $id)
{
$dir = dirname($path);
if (!file_exists($dir))
make_dir($dir);

if (file_exists($path))
{
file_put_contents($path, &#39;,&#39; . $id, FILE_APPEND|LOCK_EX);
}
else
{
$table = $this->tables[$channel];
$mysql = app::loader(&#39;mysql&#39;);
$hand = opendir($dir);
while (($file = readdir($hand)))
{
if (preg_match("/{$channel}/", $file))
{
$visit = file_get_contents("{$dir}/{$file}");
$array = explode(&#39;,&#39;, $visit);
$array = array_count_values($array);
unset($array[&#39;&#39;]);

$sql = &#39;&#39;;
foreach ($array as $id => $visit)
{
$sql .="UPDATE `{$table}` SET `visit` = `visit` + {$visit} WHERE `id` = {$id} LIMIT 1;";
}
if ($sql)
{
$res = $mysql->executes($sql);
if ($res)
unlink($dir . &#39;/&#39; . $file);
}
unset($sql);
}
}

file_put_contents($path, &#39;,&#39; . $id, LOCK_EX);
}
}

}
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template