Home  >  Article  >  php教程  >  TP行为简单例子--防刷新计数器

TP行为简单例子--防刷新计数器

WBOY
WBOYOriginal
2016-06-07 11:44:551631browse

花了一段时间,总算理解了TP行为的概念,写了一个简单的防刷新的计数器,有什么不足之处,欢迎大家指正。
首先配置项目的Conf文件夹下的tags.php文件<?php <br /> return array(<br>     'view_filter'   =>  array(<br>         'Counter'<br>     ),<br>    <br> );在项目的Behavior目录下
建立CounterBehavior.class.php文件<?php <br /> /**<br>  * 计数器行为:<br>  * <br>  */<br> class CounterBehavior extends Behavior <br> {<br>     // 行为参数定义(默认值) 可在项目配置中覆盖<br>     protected $options   =  array(<br>         'Counter_ON'       => true// 是否开启计数器<br>         );<br>     public function run(&$content)<br>     {<br>         if(C('Counter_ON'))<br>         {<br>             $file=$_SERVER['DOCUMENT_ROOT'].dirname().'/counter.txt';<br>             $hits=intval(file_get_contents($file));<br>             $nums=str_split($hits);<br>             $pic="";<br>             $imgpath=dirname().'/Public/images/counter/';<br>             foreach ($nums as $num) {<br>                 $pic.="<img alt="TP行为简单例子--防刷新计数器" >";<br>             }<br>             $content = str_replace('{__Counter__}',$pic,$content);<br>             $hits++;<br>             if(!session('?counter'))<br>             {<br>                 $handle=fopen($file, "w");<br>                 flock($handle, LOCK_EX+LOCK_NB);<br>                 fwrite($handle, $hits);<br>                 flock($handle, LOCK_UN+LOCK_NB);<br>                 fclose($handle);<br>                 session('counter',time());<br>             }<br>         }<br>         else<br>         {<br>             $content = str_replace('{__Counter__}','',$content);<br>         }<br>     }<br> }然后在需要使用计数器的模板文件里加上{__Counter__}即可

附件 counter.zip ( 148.97 KB 下载:154 次 )

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
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