Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Accessing Client Request Headers

You need to access the headers from the incoming request.


Use $r->headers_in() to obtain access to the header data.

sub handler {

 my $r = shift;

 # Grab all of the headers at once...
 my %headers_in = $r->headers_in;

 # ... or get a specific header and do something with it.
 my $gzip = $r->headers_in->get('Accept-Encoding') =~ m/gzip/;


 print "The host in your URL is: ", $headers_in{'Host'}, "\n";
 print "Your browser is: ",     $headers_in{'User-Agent'}, "\n";
 print "Your browser accepts gzip encoded data\n" if $gzip;;

 return OK;


As shown in Recipe 3.3, parts of the incoming client request have their own accessor methods. For the request headers, all are stored together in a table in the Apache request record and are accessible through the headers_in() method. headers_in() returns an array of key/value pairs in a list context or an Apache::Table object in a scalar context; our sample code uses both forms.

Acceptable client request headers are defined in section 5.3 of RFC 2616 (with the exception of the Cookie header, which is described in RFC 2109). As already mentioned, in addition to the client request headers, some general and entity headers may also apply to a client request. These three classes of headers contain many more headers than those listed here in Table 3.3, but the following are the ones that you are most likely to find yourself programming against.

Table 3.3 Some HTTP Request Headers




Lists acceptable media types for the server to present in response


Lists character sets the client will accept


Lists encodings the client will accept


Lists languages the client is most interested in


A series of authorization fields


Decribes a client cookie


Name of the requested host server


The entity tag of the client's cached version of the requested resource


An HTTP-formatted date for the server to use in resource comparisons


A list of entity tags representing the client's possible cached resources


An HTTP-formatted date for the server to use in resource comparisons


An absolute or partial URI of the resource from which the current request was obtained


A string identifying the client software

Note that the best way to access or alter a header isn't necessarily by going after the raw data with headers_in(). A multitude of methods are available in mod_perl that take care of the gory work of processing and parsing the incoming headers. For instance, the Apache::File class has methods for dealing with all the conditional If-* headers. Apache::File and these headers are discussed in detail in Chapter 6.

  • + Share This
  • 🔖 Save To Your Account