日期:2008-08-31  浏览次数:20836 次

网页计数器DIY
随着网络大行其道,网页计数器也流行起来。事实上大多数网站均有网页计数器,用以反映该网站的访问量。计数器的来源很广,FrontPage等网页编辑器自带了网页计数器,有的站点也提供免费的计数器下载。其实熟悉了ASP编程后,自己做一个计数器很容易。下面介绍一种实现方法。

计数器原理是:在第一次使用网页时置初始值1,以后每请求网页一次,将计数器值加1。这样我们只要在服务器上放置一个文本文件counter.txt,文本文件的内容有计数器的值,以后每请求一次页面,读出文本文件的计数器的数值,加1显示,然后再将原来的值改变为加1后的值,保存到文本文件。至于初始置1,在服务器上可先不建counter.txt,在网页中,先判断服务器上是否有counter.txt文件,没有就生成counter.txt,在counter.txt中写入1,网页上显示计数器值1,完成初始置1。以后每次只要到指定目录下将counter.txt文件删除即可置初始值。
具体操作时要有显示数字0、1、2….9的图像文件,0.gif、1.gif、2.gif…9.gif,文件不能太大,一般18*25即可。将你要放计数器的网页布局设计完毕,再改成ASP文件,将下面代码输入到要显示计数器的地方,使用时,程序将自动在虚拟目录count下建立counter.txt文件。置初始值时将文件删除即可。对了,虚拟目录count必须给everyone有写的权限。
<%
Const ForReading = 1, ForWriting = 2, ForAppending =3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
filepath=server.mappath("/count")
filename=filepath+"\counter.txt"
set fs=createobject("scripting.filesystemobject")
if fs.fileexists(filename) then



    set f=fs.getfile(filename)
    Set ts = f.OpenAsTextStream(ForReading,
TristateUseDefault)
    s=ts.readline+1
    ts.close
else
    fs.createtextfile(filename)
    set f=fs.getfile(filename)
    s=1
end if

'向counter.txt中写数据
Set ts = f.OpenAsTextStream(ForWriting,
TristateUseDefault)
ts.writeline(cstr(s))
ts.close

'显示计数器
s=cstr(s+1000000)
s=mid(s,2,6)
for i=1 to 6
   response.write "<img src=../../'../images/"&mid(s,i,1)
&".gif' width='18' height='25'>"
next

%>
性急的朋友要问,你的这个计数器值显示6位计数,如果要显示8位计数,怎么办?别着急,等我讲完下一个例子我会给一个通式的。
这个计数器有一个缺点,就是每次刷新页面计数器都加1,这是因为每刷新一次页面,系统认为你重新请求页面;而且,如果你不从主页面进入网站,计数器不会改变计数。如果想要



更精确一点,只要将上面的代码略加修改,放到你的global.asa的session_onstart中,这样,只有新用户进入网站,计数器才会加1。已经进入网站的用户刷新页面,不会引起计数器计数的改变,而且不管你从哪个页面进站,计数器都能捕捉到你。
<script language=vbscript runat=server>
sub application_onstart
filepath=server.mappath("/count")
filename=filepath+"\counter.txt"
set fs=createobject("scripting.filesystemobject")
if not fs.fileexists(filename) then
  fs.createtextfile(filename)
    set f=fs.getfile(filename)
           s=1
Set ts = f.OpenAsTextStream(2, -2)
ts.writeline(cstr(s))
ts.close
          else
    set f=fs.getfile(filename)
    Set ts = f.OpenAsTextStream(1, -2)
    s=ts.readline+1
    ts.close
end if
application(“visitor”)=s
end sub

sub session_onstart
session.timeout=5
application(“visitor”)=application(“visitor”)+1
set f=fs.getfile(filename)
     Set ts = f.OpenAsTextStream(2, -2)
      


ts.writeline (cstr(application(“visitor”)))
ts.close
end sub
</script>
在网页相应部分根据application(“visitor”)的值显示计数器的图像。
<%
s=cstr(application("visitor")+10^6)
s=mid(s,2,6)
for i=1 to 6
   response.write "<img src=../../'../images/"
&mid(s,i,1)&".gif' width='18' height='25'>"
next
%>
要显示n位计数器只要将上面代码改为:
<%
s=cstr(application(“visitor”)+10 ^n)
s=mid(s,2,n)
for I=1 to n
   response.write "<img src=../../'../images/"
&mid(s,i,1)&".gif' width='18' height='25'>"
next
%&g