PHP简单计数器实例程序
在php中我们有时自己会写简单的网站页面访问统计器了,下面小编来给大家介绍利用PHP实现计数器代码,希望此方法对大家有帮助。
让我们在首页上加上一个计数器,有利于演示怎样读写文件以及创建自己的函数,counter.inc包含以下代码:
- <?
-
-
-
- function get_hitcount($counter_file)
- {
-
-
-
-
- $count=0;
-
- if ( file_exists($counter_file) )
- {
- $fp=fopen($counter_file,"r");
-
- $count=0 fgets($fp,20);
-
- fclose($fp);
-
- }
-
- $count ;
-
- $fp=fopen($counter_file,"w");
- fputs($fp,$count);
- fclose($fp);
- # 返回计数值
- return ($count);
- }
- ?>
然后我们更改front.php3文件以显示这个计数器:
- <?
- include("include/counter.inc");
-
- printf ("<CENTER><B>d</B></CENTER> <BR> n",
- get_hitcount("counter.txt"));
- include("include/footer.inc");
- ?>
例2,代码如下:
1)文本计数器
- <?php
- $countfile="/count.txt";
- if (!file_exists($countfile)){
- exec( "echo 0 > $countfile");
- }
- $fp = fopen($countfile,"rw");
- $length=filesize($countfile);
- $num = fgets($fp,$length);
- $num += 1;
- exec( "rm -rf $countfile");
- exec( "echo $num > $countfile");
- PRint "访问量总计:"."$num"."人次";
- ?>
2)图形计数器
- <?
- $countfile="/count-num.txt";
- if (!file_exists($countfile))
- {exec( "echo 0 > $countfile");}
- $fp = fopen($countfile,"rw");
- $length=filesize($countfile);
- $num = fgets($fp,$length);
- $num += 1;
- exec( "rm -rf $countfile");
- exec( "echo $num > $countfile");
- $len_str = strlen($num);
- for($i=0;$i<$len_str;$i++){
- $each_num = substr($num,$i,1);
- $out_str = $out_str . "<img src="$each_num.gif">";
- }
- print "访问量总计:"."$out_str"."人次";