0

我正在尝试根据 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);
4

1 回答 1

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);

这将直接在浏览器中显示致命错误,因此您不必在网络服务器日志中四处寻找。但是,不要生产代码中启用该fatalsToBrowser选项,因为它可能会向攻击者泄露应用程序的内部工作原理。

于 2013-10-01T14:47:02.370 回答