我正在尝试根据IF条件发送http 404状态代码。但是,在客户端我看到http 500错误。 在我的apach2错误日志中,我看到格式错误的标题。 看了很多次我的代码,我无法弄清楚出了什么问题! 任何人都可以建议我如何向客户发送404消息?
以下是我的perl代码:
#!/usr/bin/perl
use CGI qw(:standard);
use strict;
use warnings;
use Carp;
use File::Copy qw( copy );
use File::Spec::Functions qw( catfile );
use POSIX qw(strftime);
use Time::Local;
use HTTP::Status qw(:constants :is status_message);
use Digest::MD5 qw(md5 md5_hex md5_base64);
use File::Basename;
use URI;
my $extfile = '/home/suresh/clientrequest.txt';
open(FH, ">>$extfile") or die "Cannot open file";
my $query = CGI->new;
my $stcode = status_message(200);
my $uri =$ENV{'REQUEST_URI'};
my $rdate =strftime("%a, %d %b %Y %H:%M:%S %Z", localtime());
print FH "Got Following Headers:\n";
print FH $ENV{'REQUEST_URI'}, "\n";
my $dir = '/home/suresh/Assets/';
my $nffFile = fileparse ("$uri", qr/\.[^.]*/);
my $fullFname = $nffFile . ".nff";
my $path = catfile($dir, $fullFname);
print FH "fullname:", $fullFname, "\n";
#Search requested asset files
opendir(DIR, $dir);
my @files = readdir(DIR);
if (grep($_=~/$fullFname/,@files)){
print FH "Found the file: ", $fullFname, "\n";
open my $fh, '<:raw', $path;
print "$ENV{SERVER_PROTOCOL} 200 $stcode";
print $query->header(
-'Date'=> $rdate,
-'Content-Type'=>'application/octet-stream',
-'Connection'=>'Keep-Alive',
-'attachment'=>$path,
);
binmode STDOUT, ':raw';
copy $fh => \*STDOUT;
close $fh
or die "Cannot close '$path': $!";
}else {
$stcode = status_message(404);
print "$ENV{'SERVER_PROTOCOL'} 404 $stcode\n";
print $query->header(
-'Server'=>$ENV{'SERVER_SOFTWARE'},
-'Content-type'=>'text/plain',
);
}
closedir(DIR);
答案 0 :(得分:5)
您应首先打印标题,。否则,浏览器将不知道如何处理您发送给它的内容。而不是:
print "$ENV{SERVER_PROTOCOL} 200 $stcode";
print $query->header( ... );
这样做:
print $query->header( ... );
print "$ENV{SERVER_PROTOCOL} 200 $stcode";
此外,您可以使用CGI.pm指定HTTP状态代码:
print $query->header( -status => '404 Not Found' );
调试CGI应用程序的一个小提示:更改
use Carp;
到
use CGI::Carp qw(fatalsToBrowser);
这将直接在浏览器中显示致命错误,因此您无需在网络服务器日志中搜索。但是, NOT 会在生产代码中启用fatalsToBrowser
选项,因为它可以向攻击者揭示应用程序的内部工作方式。