mod_perl logo perl icon
previous page: Apache2::RequestRec - Perl API for Apache request record accessorspage up: mod_perl 2.0 APInext page: Apache2::Response - Perl API for Apache HTTP request response methods

Apache2::RequestUtil - Perl API for Apache request record utils






The mod_perl Developer's Cookbook

The mod_perl Developer's Cookbook

By Geoffrey Young, Paul Lindner, Randy Kobes
mod_perl Pocket Reference

mod_perl Pocket Reference

By Andrew Ford
Writing Apache Modules with Perl and C

Writing Apache Modules with Perl and C

By Lincoln Stein, Doug MacEachern
Embedding Perl in HTML with Mason

Embedding Perl in HTML with Mason

By Dave Rolsky, Ken Williams
mod_perl2 User's Guide

mod_perl2 User's Guide

By Stas Bekman, Jim Brandt
Practical mod_perl

Practical mod_perl

By Stas Bekman, Eric Cholet


Table of Contents

Synopsis

  use Apache2::RequestUtil ();
  
  # add httpd config dynamically
  $r->add_config(['require valid-user']);
  
  # dump the request object as a string
  print $r->as_string();
  
  # default content_type
  $content_type = $r->default_type();
  
  # get PerlSetVar/PerlAddVar values
  @values = $r->dir_config->get($key);
  
  # get server docroot
  $docroot = $r->document_root();
  
  # set server docroot
  $r->document_root($new_root);
  
  # what are the registered perl handlers for a given phase
  my @handlers = @{ $r->get_handlers('PerlResponseHandler') || [] };
  
  # push a new handler for a given phase
  $r->push_handlers(PerlCleanupHandler => \&handler);
  
  # set handlers for a given phase (resetting previous values)
  $r->set_handlers(PerlCleanupHandler => []);
  
  # what's the request body limit
  $limit = $r->get_limit_req_body();
  
  # server and port names
  $server = $r->get_server_name();
  $port   = $r->get_server_port();
  
  # what string Apache is going to send for a given status code
  $status_line = Apache2::RequestUtil::get_status_line(404);
  
  # are we in the main request?
  $is_initial = $r->is_initial_req();
  
  # directory level PerlOptions flags lookup
  $r->subprocess_env unless $r->is_perl_option_enabled('SetupEnv');
  
  # current <Location> value
  $location = $r->location();
  
  # merge a <Location> container in a request object
  $r->location_merge($location);
  
  # create a new Apache2::RequestRec object
  $r = Apache2::RequestRec->new($c);
  
  # tell the client not to cache the response
  $r->no_cache($boolean);
  
  # share perl objects by reference like $r->notes
  $r->pnotes($key => [$obj1, $obj2]);
  
  # get HTML signature
  $sig = $r->psignature($prefix);
  
  # get the global request object (requires PerlOptions +GlobalRequest)
  $r = Apache2::RequestUtil->request;
  
  # insert auth credentials into the request as if the client did that
  $r->set_basic_credentials($username, $password);
  
  # slurp the contents of $r->filename
  my $content = ${ $r->slurp_filename() };
  
  # terminate the current child after this request
  $r->child_terminate();


TOP

Description

Apache2::RequestUtil provides the Apache request object utilities API.



TOP

API



TOP

add_config

Dynamically add Apache configuration at request processing runtime:

  $r->add_config($lines);
  $r->add_config($lines, $override);
  $r->add_config($lines, $override, $path);
  $r->add_config($lines, $override, $path, $override_opts);

Configuration directives are processed as if given in a <Location> block.

See also: $s->add_config

For example:

  use Apache2::RequestUtil ();
  use Apache2::Access ();

  $r->add_config(['require valid-user']);

  # this regards the current AllowOverride setting
  $r->add_config(['AuthName secret',
                  'AuthType Basic',
                  'Options ExecCGI'],
                 $r->allow_override, $path, $r->allow_override_opts);


TOP

as_string

Dump the request object as a string

  $dump = $r->as_string();

Dumps various request and response headers (mainly useful for debugging)



TOP

child_terminate

Terminate the current worker process as soon as the current request is over

  $r->child_terminate();

This method is not supported in threaded MPMs



TOP

default_type

Retrieve the value of the DefaultType directive for the current request. If not set text/plain is returned.

  $content_type = $r->default_type();


TOP

dir_config

$r->dir_config() provides an interface for the per-directory variable specified by the PerlSetVar and PerlAddVar directives, and also can be manipulated via the APR::Table methods.

  $table  = $r->dir_config();
  $value  = $r->dir_config($key);
  @values = $r->dir_config->get($key);
  $r->dir_config($key, $val);

The keys are case-insensitive.

  $apr_table = $r->dir_config();

dir_config() called in a scalar context without the $key argument returns a HASH reference blessed into the APR::Table class. This object can be manipulated via the APR::Table methods. For available methods see the APR::Table manpage.

  $value = $r->dir_config($key);

If the $key argument is passed in the scalar context only a single value will be returned. Since the table preserves the insertion order, if there is more than one value for the same key, the oldest value assosiated with the desired key is returned. Calling in the scalar context is also much faster, as it'll stop searching the table as soon as the first match happens.

  @values = $r->dir_config->get($key);

To receive a list of values you must use get() method from the APR::Table class.

  $r->dir_config($key => $val);

If the $key and the $val arguments are used, the set() operation will happen: all existing values associated with the key $key (and the key itself) will be deleted and $value will be placed instead.

  $r->dir_config($key => undef);

If $val is undef the unset() operation will happen: all existing values associated with the key $key (and the key itself) will be deleted.



TOP

document_root

Retrieve the document root for this server

  $docroot = $r->document_root();
  $docroot = $r->document_root($new_root);


TOP

get_handlers

Returns a reference to a list of handlers enabled for a given phase.

  $handlers_list = $r->get_handlers($hook_name);

See also: $s->add_config

For example:

A list of handlers configured to run at the response phase:

  my @handlers = @{ $r->get_handlers('PerlResponseHandler') || [] };


TOP

get_limit_req_body

Return the limit on bytes in request msg body

  $limit = $r->get_limit_req_body();


TOP

get_server_name

Get the current request's server name

  $server = $r->get_server_name();

For example, consruct a hostport string:

  use Apache2::RequestUtil ();
  my $hostport = join ':', $r->get_server_name, $r->get_server_port;


TOP

get_server_port

Get the current server port

  $port = $r->get_server_port();

For example, consruct a hostport string:

  use Apache2::RequestUtil ();
  my $hostport = join ':', $r->get_server_name, $r->get_server_port;


TOP

get_status_line

Return the Status-Line for a given status code (excluding the HTTP-Version field).

  $status_line = Apache2::RequestUtil::get_status_line($status);

For example:

  use Apache2::RequestUtil ();
  print Apache2::RequestUtil::get_status_line(400);

will print:

  400 Bad Request


TOP

is_initial_req

Determine whether the current request is the main request or a sub-request

  $is_initial = $r->is_initial_req();


TOP

is_perl_option_enabled

check whether a directory level PerlOptions flag is enabled or not.

  $result = $r->is_perl_option_enabled($flag);

For example to check whether the SetupEnv option is enabled for the current request (which can be disabled with PerlOptions -SetupEnv) and populate the environment variables table if disabled:

  $r->subprocess_env unless $r->is_perl_option_enabled('SetupEnv');

See also: PerlOptions and the equivalent function for server level PerlOptions flags.



TOP

location

Get the path of the <Location> section from which the current Perl*Handler is being called.

  $location = $r->location();


TOP

location_merge

Merge a given <Location> container into the current request object:

  $ret = $r->location_merge($location);

Useful for insertion of a configuration section into a custom Apache2::RequestRec object, created via the Apache2::RequestRec->new() method. See for example the Command Server protocol example.



TOP

new

Create a new Apache2::RequestRec object.

  $r = Apache2::RequestRec->new($c);
  $r = Apache2::RequestRec->new($c, $pool);

It's possible to reuse the HTTP framework features outside the familiar HTTP request cycle. It's possible to write your own full or partial HTTP implementation without needing a running Apache server. You will need the Apache2::RequestRec object in order to be able to reuse the rich functionality supplied via this object.

See for example the Command Server protocol example which reuses HTTP AAA model under non-HTTP protocol.



TOP

no_cache

Add/remove cache control headers:

  $prev_no_cache = $r->no_cache($boolean);

This method should be invoked before any response data has been sent out.



TOP

pnotes

Share Perl variables between Perl HTTP handlers

  # to share variables by value and not reference, $val should be a lexical.
  $old_val  = $r->pnotes($key => $val);
  $val      = $r->pnotes($key);
  $hash_ref = $r->pnotes();

Note: sharing variables really means it. The variable is not copied. Only its reference count is incremented. If it is changed after being put in pnotes that change also affects the stored value. The following example illustrates the effect:

  my $v=1;                     my $v=1;
  $r->pnotes( 'v'=>$v );       $r->pnotes->{v}=$v;
  $v++;                        $v++;
  my $x=$r->pnotes('v');       my $x=$r->pnotes->{v};

In both cases $x is 2 not 1. See also Apache2::SafePnotes on CPAN.

There has been a lot of discussion advocating for pnotes sharing variables by value and not reference. Sharing by reference can create 'spooky action at a distance' effects when the sharing is assumed to share a copy of the value. Tim Bunce offers the following summary and suggestion for sharing by value.

What's wrong with this code:

  sub foo {
      my ($r, $status, $why) = @_;
      $r->pnotes('foo', ($why) ? "$status:$why" : $status);
      return;
  }

Nothing, except it doesn't work as expected due to this pnotes bug: If the same code is called in a sub-request then the pnote of $r->prev is magically updated at a distance to the same value!

Try explain why that is to anyone not deeply familar with perl internals!

The fix is to avoid pnotes taking a ref to the invisible op_targ embededed in the code by passing a simple lexical variable as the actual argument. That can be done in-line like this:

  sub mark_as_internally_redirected {
      my ($r, $status, $why) = @_;
      $r->pnotes('foo', my $tmp = (($why) ? "$status:$why" : $status));
      return;
  }

This method provides functionality similar to (Apache2::RequestRec::notes), but values can be any Perl variables. That also means that it can be used only between Perl modules.

The values get reset automatically at the end of each HTTP request.

Examples:

Set a key/value pair:

  $r->pnotes(foo => [1..5]);

Get the value:

  $val = $r->pnotes("foo");

$val now contains an array ref containing 5 elements (1..5).

Now change the existing value:

  $old_val = $r->pnotes(foo => ['a'..'c']);
  $val = $r->pnotes("foo");

$old_val now contains an array ref with 5 elements (1..5) and $val contains an array ref with 3 elements 'a', 'b', 'c'.

Alternatively you can access the hash reference with all pnotes values:

  $pnotes = $r->pnotes;

Now we can read what's in there for the key foo:

  $val = $pnotes->{foo};

and as before $val still gives us an array ref with 3 elements 'a', 'b', 'c'.

Now we can add elements to it:

  push @{ $pnotes{foo} }, 'd'..'f';

and we can try to retrieve them using the hash and non-hash API:

  $val1 = $pnotes{foo};
  $val2 = $r->pnotes("foo");

Both $val1 and $val2 contain an array ref with 6 elements (letters 'a' to 'f').

Finally to reset an entry you could just assign undef as a value:

  $r->pnotes(foo => undef);

but the entry for the key foo still remains with the value undef. If you really want to completely remove it, use the hash interface:

  delete $r->pnotes->{foo};


TOP

psignature

Get HTML describing the address and (optionally) admin of the server.

  $sig = $r->psignature($prefix);


TOP

request

Get/set the ( Apache2::RequestRec object ) object for the current request.

  $r = Apache2::RequestUtil->request;
       Apache2::RequestUtil->request($new_r);

The get-able part of this method is only available if PerlOptions +GlobalRequest is in effect or if Apache2->request($new_r) was called earlier. So instead of setting PerlOptions +GlobalRequest, one can set the global request from within the handler.



TOP

push_handlers

Add one or more handlers to a list of handlers to be called for a given phase.

  $ok = $r->push_handlers($hook_name => \&handler);
  $ok = $r->push_handlers($hook_name => ['Foo::Bar::handler', \&handler2]);

Examples:

A single handler:

  $r->push_handlers(PerlResponseHandler => \&handler);

Multiple handlers:

  $r->push_handlers(PerlFixupHandler => ['Foo::Bar::handler', \&handler2]);

Anonymous functions:

  $r->push_handlers(PerlLogHandler => sub { return Apache2::Const::OK });


TOP

set_basic_credentials

Populate the incoming request headers table (headers_in) with authentication headers for Basic Authorization as if the client has submitted those in first place:

  $r->set_basic_credentials($username, $password);

See for example the Command Server protocol example which reuses HTTP AAA model under non-HTTP protocol.



TOP

set_handlers

Set a list of handlers to be called for a given phase. Any previously set handlers are forgotten.

  $ok = $r->set_handlers($hook_name => \&handler);
  $ok = $r->set_handlers($hook_name => ['Foo::Bar::handler', \&handler2]);
  $ok = $r->set_handlers($hook_name => []);
  $ok = $r->set_handlers($hook_name => undef);

See also: $s->add_config

Examples:

A single handler:

  $r->set_handlers(PerlResponseHandler => \&handler);

Multiple handlers:

  $r->set_handlers(PerlFixupHandler => ['Foo::Bar::handler', \&handler2]);

Anonymous functions:

  $r->set_handlers(PerlLogHandler => sub { return Apache2::Const::OK });

Reset any previously set handlers:

  $r->set_handlers(PerlCleanupHandler => []);

or

  $r->set_handlers(PerlCleanupHandler => undef);


TOP

slurp_filename

Slurp the contents of $r->filename:

  $content_ref = $r->slurp_filename($tainted);

Note that if you assign to $r->filename you need to update its stat record.



TOP

See Also

mod_perl 2.0 documentation.



TOP

Copyright

mod_perl 2.0 and its core modules are copyrighted under The Apache Software License, Version 2.0.



TOP

Authors

The mod_perl development team and numerous contributors.






TOP
previous page: Apache2::RequestRec - Perl API for Apache request record accessorspage up: mod_perl 2.0 APInext page: Apache2::Response - Perl API for Apache HTTP request response methods