PHP简单计数器实例程序
让我们在首页上加上一个计数器。有利于演示怎样读写文件以及创建自己的函数。counter.inc包含以下代码:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy1563')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy1563><?
/*
|| 一个简单的计数器
*/
function get_hitcount($counter_file)
{
/* 将计数器归零
这样如果计数器还未被使用,初始值将是1
你当然也可以把初始值设成20000来骗人咯
*/
$count=0;
// 如果存放计数器文件已经存在,读取其中的内容
if ( file_exists($counter_file) )
{
$fp=fopen($counter_file,"r");
// 我们只取了前20位,希望你的站点不要太受欢迎啊
$count=0 fgets($fp,20);
// 由于函数fgets()返回字符串,我们可以通过加0的方法将其自动转换为整数
fclose($fp);
// 对文件操作完毕
}
// 增加一次计数值
$count ;
// 将新的计数值写入文件
$fp=fopen($counter_file,"w");
fputs($fp,$count);
fclose($fp);
# 返回计数值
return ($count);
}
?>
然后我们更改front.php3文件以显示这个计数器:
<?
include("include/counter.inc");
// 我把计数值放在文件counter.txt中,读出并输出
printf ("<CENTER><B>d</B></CENTER> <BR> n",
get_hitcount("counter.txt"));
include("include/footer.inc");
?>
例2
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy7941')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy7941>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"."人次"; //显示访问次数
您可能感兴趣的文章:
php定时执行任务的简单实例
深入php设计模式实例详解
php代码生成器好用吗
php采集程序
PHP定时更新程序实现代码
第一章 PHP简介
PHP简单计数器实例程序
一个简单的php 文本计数器的代码
php计数器的简单代码举例
php 权重计算方法(抽奖)