CGI::Header - Adapter for CGI::header() function
use CGI::Header; # CGI.pm-compatible HTTP header properties my $header = { -attachment => 'foo.gif', -charset => 'utf-7', -cookie => [ $cookie1, $cookie2 ], # CGI::Cookie objects -expires => '+3d', -nph => 1, -p3p => [qw/CAO DSP LAW CURa/], -target => 'ResultsWindow', -type => 'image/gif' }; # create a CGI::Header object my $h = CGI::Header->new( $header ); # update $header $h->set( 'Content-Length' => 3002 ); $h->delete( 'Content-Disposition' ); $h->clear; $h->header; # same reference as $header
This module is a utility class to manipulate a hash reference which CGI's header() function receives. This class is, so to speak, a subclass of Hash because the function behaves like a hash, while Perl5 doesn't provide a built-in class called Hash.
header()
This module isn't the replacement of the function. Although this class implements as_string() method, the function should stringify the reference in most cases.
as_string()
This module can be used in the following situation:
For exmaple, CGI::Application implements header_add() method which can be used to add CGI.pm-compatible HTTP header properties. Instances of CGI applications often hold those properties.
header_add()
my $header = { -type => 'text/plain' };
Since property names are case-insensitive, application developers have to normalize them manually when they specify header properties. CGI::Header normalizes them automatically.
use CGI::Header; my $h = CGI::Header->new( $header ); $h->set( 'Content-Length' => 3002 ); # add Content-Length header $header; # => { # -type => 'text/plain', # -content_length => '3002', # }
use CGI; print CGI::header( $header ); # Content-length: 3002 # Content-Type: text/plain; charset=ISO-8859-1 #
header() function just stringifies given header properties. This module can be used to generate PSGI-compatible header array references. See also flatten().
flatten()
Given a header hash reference, returns a CGI::Header object which holds a reference to the original given argument:
my $header = { -type => 'text/plain' }; my $h = CGI::Header->new( $header ); $h->header; # same reference as $header
The object updates the reference when called write methods like set(), delete() or clear():
set()
delete()
clear()
# updates $header $h->set( 'Content-Length' => 3002 ); $h->delete( 'Content-Disposition' ); $h->clear;
A shortcut for:
my $header = CGI::Header->new({ -type => 'text/plain', ... });
Returns the header hash reference associated with this CGI::Header object.
Rebuilds the header hash to normalize parameter names without changing the reference. Returns this object itself. If parameter names aren't normalized, the methods listed below won't work as you expect.
my $h1 = $header->header; # => { # '-content_type' => 'text/plain', # 'Set-Cookie' => 'ID=123456; path=/', # 'expires' => '+3d', # '-target' => 'ResultsWindow', # '-content-length' => '3002' # } $header->rehash; my $h2 = $header->header; # same reference as $h1 # => { # '-type' => 'text/plain', # '-cookie' => 'ID=123456; path=/', # '-expires' => '+3d', # '-target' => 'ResultsWindow', # '-content_length' => '3002' # }
Normalized parameter names are:
'Content-Length' -> 'content-length'
'content-length' -> '-content-length'
'-content-length' -> '-content_length'
CGI::header() also accepts aliases of parameter names. This module converts them as follows:
CGI::header()
'-content_type' -> '-type' '-set_cookie' -> '-cookie' '-cookies' -> '-cookie' '-window_target' -> '-target'
NOTE: new() doesn't check whether parameter names are normalized or not at all, and so you have to rehash() the header hash explicitly when you aren't sure that they are normalized.
new()
rehash()
Get or set the value of the header field. The header field name ($field) is not case sensitive. You can use underscores as a replacement for dashes in header names.
$field
# field names are case-insensitive $header->get( 'Content-Length' ); $header->get( 'content-length' );
The $value argument may be a plain string or a reference to an array of CGI::Cookie objects for the Set-Cookie header.
$value
$header->set( 'Content-Length' => 3002 ); my $content_length = $header->get( 'Content-Length' ); # => 3002 # $cookie1 and $cookie2 are CGI::Cookie objects $header->set( 'Set-Cookie' => [$cookie1, $cookie2] ); my $cookies = $header->get( 'Set-Cookie' ); # => [ $cookie1, $cookie2 ]
Returns a Boolean value telling whether the specified field exists.
if ( $header->exists('ETag') ) { ... }
Deletes the specified field form CGI response headers. Returns the value of the deleted field.
my $value = $header->delete( 'Content-Disposition' ); # => 'inline'
This will remove all header fields.
Returns true if the header contains no key-value pairs.
$header->clear; if ( $header->is_empty ) { # true ... }
Returns a copy of this CGI::Header object. It's identical to:
my %copy = %{ $header->header }; # shallow copy my $clone = CGI::Header->new( \%copy );
Can be used to turn the page into an attachment. Represents suggested name for the saved file.
$header->attachment( 'genome.jpg' ); my $filename = $header->attachment; # => "genome.jpg"
In this case, the outgoing header will be formatted as:
Content-Disposition: attachment; filename="genome.jpg"
Represents P3P tags. The parameter can be an array or a space-delimited string. Returns a list of P3P tags. (In scalar context, returns the number of P3P tags.)
$header->p3p_tags(qw/CAO DSP LAW CURa/); # or $header->p3p_tags( 'CAO DSP LAW CURa' ); my @tags = $header->p3p_tags; # => ("CAO", "DSP", "LAW", "CURa") my $size = $header->p3p_tags; # => 4
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP LAW CURa"
The Expires header gives the date and time after which the entity should be considered stale. You can specify an absolute or relative expiration interval. The following forms are all valid for this field:
$header->expires( '+30s' ); # 30 seconds from now $header->expires( '+10m' ); # ten minutes from now $header->expires( '+1h' ); # one hour from now $header->expires( 'now' ); # immediately $header->expires( '+3M' ); # in three months $header->expires( '+10y' ); # in ten years time # at the indicated time & date $header->expires( 'Thu, 25 Apr 1999 00:40:33 GMT' );
If set to a true value, will issue the correct headers to work with a NPH (no-parse-header) script. Specifically, the Date and Server headers will be added to response headers automatically.
$header->nph( 1 ); my $nph = $header->nph; # => 1 my $server = $header->get('Server'); # => $ENV{SERVER_SOFTWARE} my $date = $header->get('Date'); # => HTTP-Date
NOTE: You can't modify those headers when $header->nph is true:
$header->nph
$header->nph(1); # wrong $header->set( 'Server' => 'Apache/1.3.27 (Unix)' ); $header->set( 'Date' => 'Thu, 25 Apr 1999 00:40:33 GMT' ); $header->delete( 'Server' ); $header->delete( 'Date' );
Returns the list of distinct field names present in the header in a random order. The field names have case as returned by CGI::header().
my @fields = $header->field_names; # => ( 'Set-Cookie', 'Content-length', 'Content-Type' )
Apply a subroutine to each header field in turn. The callback routine is called with two parameters; the name of the field and a value. If the Set-Cookie header is multi-valued, then the routine is called once for each value. Any return values of the callback routine are ignored.
my @lines; $header->each(sub { my ( $field, $value ) = @_; push @lines, "$field: $value"; }); print join @lines, "\n"; # Content-length: 3002 # Content-Type: text/plain
Returns pairs of fields and values. This method flattens the Set-Cookie headers recursively by default. The optional $is_recursive argument determines whether to flatten them recursively.
$is_recursive
my $header = CGI::Header->new( -cookie => ['cookie1', 'cookie2'] ); $header->flatten; # => ( # 'Set-Cookie' => 'cookie1', # 'Set-Cookie' => 'cookie2', # 'Date' => 'Thu, 25 Apr 1999 00:40:33 GMT', # 'Content-Type' => 'text/html' # ) $header->flatten(0); # => ( # 'Set-Cookie' => ['cookie1', 'cookie2'], # 'Date' => 'Thu, 25 Apr 1999 00:40:33 GMT', # 'Content-Type' => 'text/html' # )
This method can be used to generate PSGI-compatible header array references. For example,
use parent 'CGI'; use CGI::Header; sub psgi_header { my $self = shift; my $header = CGI::Header->new(@_)->rehash; my $status = $header->delete('Status') || '200 OK'; $status =~ s/\D*$//; $status, [ $header->flatten ]; }
Strictly speaking, you have to check charset() attribute of CGI.pm. In addition, if $header->nph is true, $header->flatten will return the Server header which psgi_header() shouldn't return. Moreover, this method depends on a global variable %ENV.
charset()
$header->flatten
psgi_header()
%ENV
See also CGI::Emulate::PSGI, CGI::PSGI.
Returns the header fields as a formatted MIME header. The optional $eol parameter specifies the line ending sequence to use. The default is \015\012.
$eol
\015\012
When valid multi-line headers are included, this method will always output them back as a single line, according to the folding rules of RFC 2616: the newlines will be removed, while the white space remains.
Unlike CGI.pm, when invalid newlines are included, this module removes them instead of throwing exceptions.
If $header->nph is true, the Status-Line will be added to the beginning of response headers automatically.
$header->nph(1); $header->as_string; # HTTP/1.1 200 OK # Server: Apache/1.3.27 (Unix) # ...
use CGI::Header; my $header = { -type => 'text/plain' }; tie my %header => 'CGI::Header' => $header; # update $header $header{'Content-Length'} = 3002; delete $header{'Content-Disposition'}; %header = (); tied( %header )->header; # same reference as $header
Above methods are aliased as follows:
TIEHASH -> new FETCH -> get STORE -> set DELETE -> delete CLEAR -> clear EXISTS -> exists SCALAR -> !is_empty
You can also iterate through the tied hash:
my @fields = keys %header; my @values = values %header; my ( $field, $value ) = each %header;
See also perltie.
# wrong $header->set( 'Content-Type' => undef ); $header->set( 'Content-Type' => q{} );
Use delete() instead:
$header->delete( 'Content-Type' );
# wrong $header->set( 'Expires' => '+3d' );
Use expires() instead:
$header->expires( '+3d' );
because the following behavior will surprize us:
$header->set( 'Expires' => '+3d' ); my $value = $header->get( 'Expires' ); # => "Thu, 25 Apr 1999 00:40:33 GMT" (not "+3d")
CGI::header() restricts where the policy-reference file is located, and so you can't modify the location (/w3c/p3p.xml). The following code doesn't work as you expect:
/w3c/p3p.xml
# wrong $header->set( 'P3P' => '/path/to/p3p.xml' );
You're allowed to set P3P tags using p3p_tags().
p3p_tags()
CGI, Plack::Util, HTTP::Headers
There are no known bugs in this module. Please report problems to ANAZAWA (anazawa@cpan.org). Patches are welcome.
Ryo Anazawa (anazawa@cpan.org)
This module is free software; you can redistibute it and/or modify it under the same terms as Perl itself. See perlartistic.
To install CGI::Header, copy and paste the appropriate command in to your terminal.
cpanm
cpanm CGI::Header
CPAN shell
perl -MCPAN -e shell install CGI::Header
For more information on module installation, please visit the detailed CPAN module installation guide.