<?php
// 访客计数器函数
function counter() {
!empty($_GET['weburl']) || die('weburl不能为空');
$weburl = $_GET['weburl']; $file = '/usr/local/apache/htdocs/MyTests/counter.txt';
if (! file_exists($file)) {
$num = 1;
$cf = fopen($file, 'w');
fwrite($cf, $weburl.' '.$num);
fclose($cf);
} else {
$cf = fopen($file, 'rw');
$num = fgets($cf);
$num = substr($num, 15);
fclose($cf); ++$num;
$cf = fopen($file, 'w');
fwrite($cf, $num);
fclose($cf);
}
}?>
<html>
<head>
<title>访客计数器</title>
</head>
<body>
<center>
<h1>欢迎访问</h1><br />
<form action="counter()" name="url-form" method="get">
<div>
<input type="text" name="weburl" size="15" />
<input type="submit" name="Submit" value="提交" />
</div>
</form>
<hr />
<font size="7" color="red">
您是第<?php //echo counter() ?>位访客
</font>
</center>
</body>
</html>
我想实现一个输入不同的IP地址并提交后,在“您是第...位访客”中显示相应IP访问了多少次我用一个TXT文件存储IP地址与浏览次数,格式如下:
例:
192.168.0.22 5
192.168.5.44 10
......这个程序应该如何修改?存储PHPHTML函数Color
// 访客计数器函数
function counter() {
!empty($_GET['weburl']) || die('weburl不能为空');
$weburl = trim($_GET['weburl']);
$pattern = "/((25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(25[0-5]|2[0-4]\d|1?\d?\d)/";
//对录入的ip格式进行判断
if(! preg_match($pattern,$weburl))
die('IP地址格式不正确;');
//使ip长度固定
$arr = explode('.',$weburl);
for($i=0;$i<4;$i++){
$arr[$i] = str_pad($arr[$i],3,' ',STR_PAD_LEFT);
}
$weburl = join('.',$arr); $file = 'counter.txt';
if (! file_exists($file)) {
$num = 1;
$cf = fopen($file, 'w');
fwrite($cf, $weburl.'-'.$num);
fclose($cf);
return $num;
} else {
$cf = fopen($file, 'r+');
while(!feof ($cf)){
$str1 = fgets($cf);
$str2 = substr($str1,0,strpos($str1,'-'));
if($weburl == $str2){
$len = strlen($str1);
$num = (int) trim(substr($str1,strpos($str1,'-')+1));
$num++;
$str1 = $weburl.'-'.$num;
//如果存在则把指针返回到该行前,覆盖写入内容,实现修改
fseek($cf,-$len,SEEK_CUR);
fwrite($cf,$str1);
fseek($cf,$len,SEEK_CUR);
fclose($cf);
return $num;
}
}
//未找到则在末尾换行增加一行记录
fwrite($cf, "\r\n".$weburl.'-1');
return 1;
}
}?>
<html>
<head>
<title>访客计数器</title>
</head>
<body>
<center>
<h1>欢迎访问</h1><br />
<form action="" name="url-form" method="get">
<div>
<input type="text" name="weburl" size="15" />
<input type="submit" name="Submit" value="提交" />
</div>
</form>
<hr />
<font size="7" color="red">
您是第<?php echo counter(); ?>位访客
</font>
</center>
</body>
</html>