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.

I get how to make the header of a request (using 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 -H "HeaderAttribute: value"


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_HOST: localhost
HTTP_USER_AGENT: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/ libidn/1.18

In addition to the 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') {

They're supplied as environment variables, such as


You may have to do something to configure your web server to supply such a variable, though.

Need Your Help