检查CGI脚本的错误

带有错误的脚本

#!/usr/bin/perl
$report_file="/cgi/report";           #设定调用的文件名
print("content-type:text/html\n\n");  #设定输出模式为TEXT/HTML
open(report_file,$report_file);       #打开和读取那个文件
read(report_file,$report_text,2048);
print(<html><head><title>日志打印报告</title></head>\n");
print("<body><pre>\n");
print("$report_text\n");
print("</pre></body></html>\n");

    这个CGI程序看起来运行得很好。但是,如果txt/passwd文件不能打开或无法 读取,这个脚本程序将产生错误或是流产,更坏的情况是它继续执行下,得到不正 确的结果。

经过再次修改的脚本(还是隐藏着错误)

#!/usr/bin/perl
#设定调用的文件名
$report_file="/cgi/report";
#设定输出模式为TEXT/HTML
print("content-type:text/html\n\n");
#尝试打开report文件
if (open(report_file,$report_file)==0)
{
   #尝试读取report文件
   if (read(report_file,$report_text,2048)>0)
   {
   #打印report文件
   print(<html><head><title>日志打印报告</title></head>\n");
   print("<body><pre>\n");
   print("$report_text\n");
   print("</pre></body></html>\n");
  
   exit(0);

   }
}
    这个脚本的错误在什么地方?原来在于编写者猜想每个调用都不会出错,它使
用open()和read()函数进行调用检测,该程序在一般情况下运行正常,但万一出现
调用错误,代码中不会告诉你的用户到底是什么原因。

比较完美的脚本

#!/usr/bin/perl
#设定调用的文件名
$report_file="/cgi/report";
#设定错误信息,与返回
sub error_fatal
{
   print("<html><head><title>错误!</title><head><body>\n");
   print("错误!请把你的情况与<a href="mailto:tryfly@163.net">webmas-
   ter</a>联系。");
   print("</body></html>\n");
   exit(-1);
}

#设定输出模式为TEXT/HTML
print("content-type:text/html\n\n");

#尝试打开report文件
if (open(report_file,$report_file)==0)
{
     print(<html><head><title>错误!</title></head>\n");
     print("<body>\n");
     print("不能打开report文件\n");
     print("</body></html>\n");
  
   exit(-1);
  }
#尝试读取report文件
if (read(report_file,$report_text,2048)<1)
{
     print(<html><head><title>错误!</title></head>\n");
     print("<body>\n");
     print("不能读取report文件\n");
     print("</body></html>\n");
  
   exit(-1);
}    
   #打印report文件
   print(<html><head><title>日志打印报告</title></head>\n");
   print("<body><pre>\n");
   print("$report_text\n");
   print("</pre></body></html>\n");
  
   exit(0);
    这段脚本是比较完美的,它每次调用时如果失败它就会告知用户出错的信息,
而且对排除CGI脚本错误有着很大的帮助。