Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I've used Perl a bit for small applications and test code, but I'm new to networking and 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. 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"

like image 689
CGInewb Avatar asked Oct 24 '10 03:10

CGInewb


People also ask

How do I view HTTP headers?

To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

Which of the given is an HTTP header frequently used in CGI programming?

HTTP Header There are few other important HTTP headers, which we will use frequently in our CGI Programming. Sr.No. The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed.

What is a HTTP request header?

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.


2 Answers

The CGI module has a http() function you can use to that purpose:

#!/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
like image 159
mfontani Avatar answered Oct 22 '22 09:10

mfontani


In addition to the CGI.pm http() method you can get HTTP headers information from the environment variables.

So in case you are using something like CGI::Minimal, which doesn't have the http method. you can do something like:

  my $header = 'HTTP_X_REQUESTED_WITH';

  if (exists $ENV{$header} && lc $ENV{$header} eq 'xmlhttprequest') {
   _do_some_ajaxian_stuff();
  }
like image 26
jira Avatar answered Oct 22 '22 09:10

jira