CGI入门教程

第二页:计数器

下面是一个简单的计数器程序:

#******** BEGIN BODY ********
open (GETCOUNT,"<count.log");            #open count log for input
$counter=<GETCOUNT>;                      #assign contents of file to $counter
close (GETCOUNT);                              #close access to file

$counter++;                                                 #increase $counter by 1.
print "$counter hits";                                #print number of hits to users screen

open (PUTCOUNT,">count.log");            #open count log for output
print PUTCOUNT ($counter);                #replace old counter value with new one
close PUTCOUNT;                                # close access to file

#******** END BODY *********

如果用SUBMIT按钮,当前页将消失,出现程序的输出页。为了在当前页上显示点击数,需要有一个页面转载时执行的程序,然后把结果潜入相同页面上。这种方法叫做Server Side Include(SSI)。

注意:不是所有的web服务器都支持SSI。有些只在页面文件以".shtml"或".html-ssi"结束才起作用,有些由于安全原因完全屏蔽了这种功能。

下面是代码的工作过程:

  • 把上面的代码拷贝到一个新的'template.txt'文件中,命名为count.cgi。
  • 建立一个包含起始点击数的文件,命名为count.log。
  • 新建一个HTML页面。
  • 插入<!--#exec cgi="count.cgi"-->。
  • 把上面3个文件上传到服务器上。
  • Telnet到perltour文件夹中,敲入chmod a+rx count.cgi。
  • 浏览这个页面,重载几次,可以看到数字的增加。

如果不起作用,直接浏览count.cgi看它是否工作。一旦CGI起作用,把页面文件重命名为.shtml扩展名。

CGI入门教程
第一页 设置口令
第二页 计数器

[第1天][第2天][第3天][第4天][第5天][第6天]