您好,欢迎访问一九零五行业门户网

php如何实现文章点击数

php 文件实现文章点击量
<?phperror_reporting(e_all);$root_path = '../';include_once($root_path . "include/config.php"); $update_time = 1800;//多长时间更新一次,单位是秒 $article_id = (isset($_get['article_id']) && is_numeric($_get['article_id']) && $_get['article_id'] > 0) ? intval($_get['article_id']) : 0;//文章的idif ($article_id > 0) { $filename = $root_path . 'log/click_log.txt'; $s = ''; if (file_exists($filename)) { $content = file_get_contents($filename); $d_ary = array(); if ($content) { $ary = explode("\n", $content); foreach ($ary as $line) { $data_ary = explode('|', $line); if (is_numeric($data_ary[0]) && is_numeric($data_ary[1])) { $d_ary[$data_ary[0]] = $data_ary[1]; } } } if (array_key_exists($article_id, $d_ary)) { $d_ary[$article_id] = $d_ary[$article_id]+1;//将当前的文章的点击数加1 } else { $d_ary[$article_id] = 1; } foreach ($d_ary as $key => $val) { $s .= $key . '|' . $val . "\n"; } } else { $s .= $article_id . '|1' . "\n";//这个是初始化记录文件 } //写记录文件 $fp = fopen($filename, "w");//加入锁定if (flock($fp, lock_ex)) { // 进行排它型锁定 fwrite($fp, $s); flock($fp, lock_un); // 释放锁定} //fwrite($fp, $s); fclose($fp); @chmod($filename, 0777); $last_update = file_get_contents('../log/last_update.txt');//取上一次更新的时间 $last_update = intval($last_update); if (($last_update + $update_time) < time()) { //以下是数据库连接操作,我用的是adodb,你可以改成你自己的 require_once("adodb.inc.php"); $db = newadoconnection("$db_type"); $db->debug = true; $adodb_fetch_mode = adodb_fetch_assoc; if (!$db->connect("$db_host", "$db_user", "$db_pass", "$db_database")) { exit('<a href="/">服务器忙,请稍候再访问</a>'); } $content = file_get_contents($filename); $d_ary = array(); if ($content) { $ary = explode("\n", $content); foreach ($ary as $line) { $data_ary = explode('|', $line); if (is_numeric($data_ary[0]) && is_numeric($data_ary[1])) { $sql = "update article set hits=hits+" . $data_ary[1] . " where id=" . $data_ary[0]; $db->execute($sql); } } } //点击数更新完了,将这个记录文件清空 $fp = fopen($filename, "w"); fwrite($fp, ''); fclose($fp); @chmod($filename, 0777); //将最后一次更新时间改为当前时间 $fp = fopen('../log/last_update.txt', "w"); fwrite($fp, time()); fclose($fp); @chmod('../log/last_update.txt', 0777); $db->close();//关闭数据库连接 } exit();}?>
首先在log目录下创建last_update.txt
内容是 1155163400,(这是time()函数生成的时间)
click_log文件的内容是像下面这样的:
13136|4413104|3123509|3211407|512141|29
第一个数字代表文章的id,第二个数字代表累积的点击数
这样做,会提高程序的执行效率,无论是动态的php页面还是html里,以
<script src="click.php?article_id=333"></script>
这种方法的页面,都很有效.
这个一般用于统计文章等内容的点击数的
一般静态页里,像上面这样用的(可以把我上面的程序存成click.php)
动态页里的话,可以把上面的代码做成一个包含文件,然后在你的文章中include进来,不过,要改一下这个php的代码,把article_id传进去.不多说了,php程序员都会知道怎么做,不懂程序的话,我讲太多也没用
前些日子因为我服务器上的mysql进程里,经常看见一大堆的update,所以就想了这种缓存更新的方式
更多相关技术文章,请访问!
其它类似信息

推荐信息