简体   繁体   English

如何在CGI脚本中访问HTTP标头请求?

[英]How do I access the HTTP Header of request in a CGI script?

I've used Perl a bit for small applications and test code, but I'm new to networking and CGI. 我已经将Perl用于小型应用程序和测试代码,但我是网络和CGI的新手。

I get how to make the header of a request (using CGI.pm and printing the results of the header() function), but haven't been able to find any info on how to access the headers being sent to my CGI script. 我得到了如何制作请求的标题(使用CGI.pm并打印header()函数的结果),但是无法找到有关如何访问发送到我的CGI脚本的标头的任何信息。 Could someone point me in the right direction? 有人能指出我正确的方向吗?

This could be from a request like this: 这可能是来自这样的请求:

curl http://127.0.0.1:80/cgi-bin/headers.cgi -H "HeaderAttribute: value"

The CGI module has a http() function you can use to that purpose: CGI模块有一个http()函数,您可以将其用于此目的:

#!/usr/bin/perl --
use strict;
use warnings;
use CGI;

my $q = CGI->new;
my %headers = map { $_ => $q->http($_) } $q->http();

print $q->header('text/plain');
print "Got the following headers:\n";
for my $header ( keys %headers ) {
    print "$header: $headers{$header}\n";
}

Try it out; 试试看; the above gives me: 以上给了我:

$ curl http://localhost/test.cgi -H "HeaderAttribute: value"
Got the following headers:
HTTP_HEADERATTRIBUTE: value
HTTP_ACCEPT: */*
HTTP_HOST: localhost
HTTP_USER_AGENT: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18

In addition to the CGI.pm http() method you can get HTTP headers information from the environment variables. 除了CGI.pm http()方法,您还可以从环境变量中获取HTTP头信息。

So in case you are using something like CGI::Minimal , which doesn't have the http method. 因此,如果您使用的是CGI :: Minimal ,它没有http方法。 you can do something like: 你可以这样做:

  my $header = 'HTTP_X_REQUESTED_WITH';

  if (exists $ENV{$header} && lc $ENV{$header} eq 'xmlhttprequest') {
   _do_some_ajaxian_stuff();
  }

They're supplied as environment variables, such as 它们作为环境变量提供,例如

HTTP_HEADERATTRIBUTE=value

You may have to do something to configure your web server to supply such a variable, though. 但是,您可能必须执行某些操作来配置Web服务器以提供此类变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM