NAME
Apache2::API::Request - Apache2 Incoming Request Access and Manipulation
SYNOPSIS
use Apache2::API::Request;
# $r is the Apache2::RequestRec object
my $req = Apache2::API::Request->new( request => $r, debug => 1 );
# or, to test it outside of a modperl environment:
my $req = Apache2::API::Request->new( request => $r, debug => 1, checkonly => 1 );
# Tells whether the connection has been aborted or not
$req->aborted;
# e.g.: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
my $accept = $req->accept;
# Returns an array object
my $all = $req->acceptable;
$req->acceptable( $array_ref );
# Returns an array object
my $all = $req->acceptables;
my $charset = $req->accept_charset;
# e.g.: gzip, deflate, br
my $encoding = $req->accept_encoding;
# en-GB,fr-FR;q=0.8,fr;q=0.6,ja;q=0.4,en;q=0.2
my $lang = $req->accept_language;
my $type = $req->accept_type;
my $version = $req->accept_version;
# GET, POST, PUT, OPTIONS, HEAD, etc
my $methods = $req->allowed;
# get an APR::Request::Apache2 object
my $apr = $req->apr;
# query string as an hash reference
my $hash_ref = $req->args; # also an APR::Request::Param::Table object
my $status = $req->args_status;
# HTTP query
my $string = $req->as_string;
my $auth = $req->auth;
my $auth = $req->authorization;
my $auth_type = $req->auth_type;
$req->auto_header(1);
# returns an APR::Request::Param::Table object similar to APR::Table
my $body = $req->body;
my $status = $req->body_status;
my $limit = $req->brigade_limit;
my $charset = $req->charset;
$req->child_terminate;
my $api_version = $req->client_api_version;
# close client connection
$req->close;
my $status_code = $req->code;
# Apache2::Connection
my $conn = $req->connection;
my $id = $req->connection_id;
# content of the request filename
my $content = $req->content;
my $encoding = $req->content_encoding;
my $langs_array_ref = $req->content_languages;
my $len = $req->content_length;
# text/plain
my $ct = $req->content_type;
# Get a Cookie object
my $cookie = $req->cookie( $name );
# Cookie::Jar object
my $jar = $req->cookies;
# get data string sent by client
my $data = $req->data;
my $formatter = $req->datetime;
my $decoded = $req->decode( $string );
my $do_not_track = $req->dnt;
my $encoded = $req->encode( $string );
$req->discard_request_body(1);
my $document_root = $req->document_root;
my $url = $req->document_uri;
# APR::Table object
my $hash_ref = $req->env;
my $headers = $req->err_headers_out;
# request filename
my $filename = $req->filename;
# APR::Finfo object
my $finfo = $req->finfo;
# e.g.: CGI/1.1
my $gateway = $req->gateway_interface;
my $code_ref = $req->get_handlers( $name );
# 404 Not Found
my $str = $req->get_status_line(404);
my $r = $req->global_request;
my $is_head = $req->header_only;
# same
my $is_head = $req->is_header_only;
my $content_type = $req->headers( 'Content-Type' );
# or (since it is case insensitive)
my $content_type = $req->headers( 'content-type' );
# or
my $content_type = $req->headers->{'Content-Type'};
$req->headers( 'Content-Type' => 'text/plain' );
# or
$req->headers->{'Content-Type'} = 'text/plain';
# APR::Table object
my $headers = $req->headers;
my $hash_ref = $req->headers_as_hashref;
my $json = $req->headers_as_json;
my $headers = $req->headers_in;
my $out = $req->headers_out;
my $hostname = $req->hostname;
my $uri_host = $req->http_host;
my $conn_id = $req->id;
my $if_mod = $req->if_modified_since;
my $if_no_match = $req->if_none_match;
my $filters = $req->input_filters;
my $enabled = $req->is_perl_option_enabled;
# running under https?
my $secure = $req->is_secure;
# JSON object
my $json = $req->json;
my $keepalive = $req->keepalive;
my $keepalives = $req->keepalives;
my $ok_languages = $req->languages;
my $nbytes = $req->length;
# APR::SockAddr object
my $addr = $req->local_addr;
my $host = $req->local_host;
my $str = $req->local_ip;
my $loc = $req->location;
$req->log_error( "Oh no!" );
# 200kb
$req->max_size(204800);
my $http_method = $req->method;
my $meth_num = $req->method_number;
# mod_perl/2.0.11
my $mod_perl = $req->mod_perl;
my $vers = $req->mod_perl_version;
my $seconds = $req->mtime;
my $req2 = $req->next;
$req->no_cache(1);
# APR::Table object
my $notes = $req->notes;
my $notes = $req->pnotes;
my $filters = $req->output_filters;
my $val = $req->param( $name );
my $hash_ref = $req->params;
my $dt = $req->parse_date( $http_date_string );
my $path = $req->path;
my $path_info = $req->path_info;
# for JSON payloads
my $hash_ref = $req->payload;
my $val = $req->per_dir_config( $my_config_name );
# APR::Pool object
my $pool = $req->pool;
my $best_lang = $req->preferred_language( $lang_array_ref );
my $req0 = $req->prev;
my $proto = $req->protocol;
$req->proxyreq( Apache2::Const::PROXYREQ_PROXY );
$req->push_handlers( $name => $code_ref );
# get hash reference from the query string using Apache2::API::Query instead of APR::Body->args
# To use APR::Body->args, call args() instead
my $hash_ref = $req->query;
my $string = $req->query_string;
my $nbytes = $req->read( $buff, 1024 );
my $notes = $req->redirect_error_notes;
my $qs = $req->redirect_query_string;
my $status = $req->redirect_status;
my $url = $req->redirect_url;
my $referrer = $req->referer;
# APR::SockAddr object
my $addr = $req->remote_addr;
my $host = $req->remote_host;
my $string = $req->remote_ip;
my $port = $req->remote_port;
$req->reply( Apache2::Const::FORBIDDEN => { message => "Get away" } );
# Apache2::RequestRec
my $r = $req->request;
my $scheme = $req->request_scheme;
# DateTime object
my $dt = $req->request_time;
my $uri = $req->request_uri;
my $filename = $req->script_filename;
my $name = $req->script_name;
my $uri = $req->script_uri;
# Apache2::ServerUtil object
my $server = $req->server;
my $addr = $req->server_addr;
my $admin = $req->server_admin;
my $hostname = $req->server_hostname;
my $name = $req->server_name;
my $port = $req->server_port;
my $proto = $req->server_protocol;
my $sig = $req->server_signature;
my $software = $req->server_software;
my $vers = $req->server_version;
$req->set_basic_credentials( $user => $password );
$req->set_handlers( $name => $code_ref );
my $data = $req->slurp_filename;
# Apache2::Connection object
my $socket = $req->socket;
my $status = $req->status;
my $line = $req->status_line;
my $dt = $req->str2datetime( $http_date_string );
my $rc = $req->subnet_of( $ip, $mask );
# APR::Table object
my $env = subprocess_env;
my $dir = $req->temp_dir;
my $r = $req->the_request;
my $dt = $req->time2datetime( $time );
say $req->time2str( $seconds );
# text/plain
my $type = $req->type;
my $raw = $req->unparsed_uri;
# Apache2::API::Request::Params
my $uploads = $req->uploads;
my $uri = $req->uri;
my $decoded = $req->url_decode( $url );
my $encoded = $req->url_encode( $url );
my $user = $req->user;
my $agent = $req->user_agent;
VERSION
v0.1.1
DESCRIPTION
The purpose of this module is to provide an easy access to various methods designed to process and manipulate incoming requests.
This is designed to work under modperl.
Normally, one would need to know which method to access across various Apache2 mod perl modules, which makes development more time consuming and even difficult, because of the scattered documentation and even sometime outdated.
This module alleviate this problem by providing all the necessary methods in one place. Also, at the contrary of Apache2 modules suit, all the methods here are die safe. When an error occurs, it will always return undef() and the error will be able to be accessed using error object, which is a Module::Generic::Exception object.
For its alter ego to manipulate outgoing HTTP response, use the Apache2::API::Response module.
Throughout this documentation, we refer to $r
as the Apache request object and $req
as an object from this module.
CONSTRUCTORS
new
This takes an optional hash or hash reference of options and instantiate a new object.
It takes the following parameters:
checkonly
If true, it will not perform the initialisation it would usually do under modperl.
debug
Optional. If set with a positive integer, this will activate verbose debugging message
max_size
Optional. This is the maximum size of the data that can be sent to us over HTTP. By default, there is no limit.
request
This is a required parameter to be sent with a value set to a Apache2::RequestRec object
METHODS
aborted
Tells whether the connection has been aborted or not, by calling "aborted" in Apache2::Connection
accept
Returns the HTTP Accept
header value, such as text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
See also "headers"
accept_charset
Sets or gets the acceptable character set. This is computed upon object instantiation by looking at the Accept
header:
Accept: application/json; version=1.0; charset=utf-8
Here, it would be utf-8
accept_encoding
Returns the HTTP Accept-Encoding
header value.
Accept-Encoding: gzip, deflate;q=1.0, *;q=0.5
Accept-Encoding: gzip, deflate, br
See also "headers" and https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
accept_language
Returns the HTTP Accept-Language
header value such as en-GB,fr-FR;q=0.8,fr;q=0.6,ja;q=0.4,en;q=0.2
See also "headers"
accept_type
Sets or gets the acceptable content type. This is computed upon object instantiation by looking at the Accept
header:
Accept: application/json; version=1.0; charset=utf-8
Here, it would be application/json
accept_version
Sets or gets the version of the api being queried. This is computed upon object instantiation by looking at the Accept
header:
Accept: application/json; version=1.0; charset=utf-8
Here, it would be 1.0
acceptable
This method parse the request header Accept
, by calling "acceptables", which could be, for example:
application/json, text/javascript, */*
And return an array object of acceptable content types.
my $all = $req->acceptable;
my $first = $req->acceptable->first;
You can also sets its array reference by passing either a list of value or an array reference.
acceptables
This takes the value from the Accept
header, splits them using "new_from_multi" in Module::Generic::HeaderValue and returns an array object of Module::Generic::HeaderValue objects with their value and param methods, which gives access to key-value pairs of possible attributes to this acceptable value.
So, if the Accept
header value was application/json, text/javascript, */*
, the array object returned would contain 3 Module::Generic::HeaderValue objects with each $hdr->value->first
method returning:
allowed
Gets or sets the allowed methods bitmask such as GET, POST, PUT, OPTIONS, HEAD, etc, by calling "allowed" in Apache2::RequestRec
It returns a bitvector of the allowed methods.
For example, if the module can handle only GET
and POST
methods it could start with:
use Apache2::API;
unless( $r->method_number == Apache2::Const::M_GET ||
$r->method_number == Apache2::Const::M_POST )
{
$r->allowed( $r->allowed | ( 1 << Apache2::Const::M_GET ) | ( 1 << Apache2::Const::M_POST ) );
return( Apache2::Const::HTTP_METHOD_NOT_ALLOWED );
}
See also "allowed_methods"
allow_methods
$req->allow_methods( $reset );
$req->allow_methods( $reset, @methods );
Provided with a reset boolean and a list of HTTP methods, and this will set the allowed methods such as GET, POST, PUT, OPTIONS, HEAD, etc, by calling "allow_methods" in Apache2::Access
If the reset boolean passed is a true value, then all the previously allowed methods are removed, otherwise they are left unchanged.
For example, to allow only GET
and POST
, notwithstanding what was set previously:
$req->allow_methods( 1, qw( GET POST ) );
It does not return anything. This is used only to set the allowed method. To retrieve them, see "allowed"
allow_options
my $bitmask = $req->allow_options;
Retrieve the bitmask value of Apache configuration directive Options
for this request, by calling "allow_options" in Apache2::Access
You would need to use Apache constants against the returned value.
For example if the configuration for the current request was:
Options None
Options Indexes FollowSymLinks
The following applies:
use Apache2::API;
$req->allow_options & Apache2::Const::OPT_INDEXES; # true
$req->allow_options & Apache2::Const::OPT_SYM_LINKS; # true
$req->allow_options & Apache2::Const::OPT_EXECCGI; # false
allow_overrides
my $bitmask = $req->allow_overrides;
Retrieve the bitmask value of AllowOverride
for this request by calling "allow_overrides" in Apache2::Access
You would need to use Apache constants against the returned value.
For example if the configuration for the current request was:
AllowOverride AuthConfig
The following applies:
use Apache2::API;
$req->allow_overrides & Apache2::Const::OR_AUTHCFG; # true
$req->allow_overrides & Apache2::Const::OR_LIMIT; # false
See also https://httpd.apache.org/docs/2.4/en/mod/core.html#allowoverride
allow_override_opts
my $bitmask = $req->allow_override_opts;
Retrieve the bitmask value of allowed Options
set by AllowOverride Options
Apache configuration directive, by calling "allow_override_opts" in Apache2::Access
You would need to use Apache constants against the returned value.
For example if the configuration for the current request was:
AllowOverride Options=Indexes,ExecCGI
The following applies:
use Apache2::API;
$req->allow_override_opts & Apache2::Const::OPT_EXECCGI; # true
$req->allow_override_opts & Apache2::Const::OPT_SYM_LINKS; # false
Note that enabling single options was introduced in Apache 2.2. For Apache 2.0 this function returns:
Apache2::Const::OPT_UNSET | Apache2::Const::OPT_ALL | Apache2::Const::OPT_INCNOEXEC | Apache2::Const::OPT_SYM_OWNER | Apache2::Const::OPT_MULTI
which corresponds to the default value (if not set) for Apache 2.2.
See also https://httpd.apache.org/docs/2.4/en/mod/core.html#allowoverride
apr
Returns a Apache2::API::Request::Param object used to access Apache mod_perl methods to manipulate request data.
args
my $hash_ref = $req->args;
my @names = $req->args;
my $first_value = $req->args( $name );
my @values = $req->args( $name );
my $table = $req->args;
# The keys are case-insensitive.
$table->set( $key => $val );
$table->unset( $key );
$table->add( $key, $val );
$val = $table->get( $key );
@val = $table->get( $key );
$table->merge( $key => $val );
$table_overlay = $table_base->overlay( $table_overlay, $pool );
$table_overlay->compress( APR::Const::OVERLAP_TABLES_MERGE );
$table_a->overlap( $table_b, APR::Const::OVERLAP_TABLES_SET );
Get or sets the query string data by calling "args" in APR::Body
With no arguments, this method returns a tied APR::Request::Param::Table object (or undef if the query string is absent) in scalar context, or the names (in order, with repetitions) of all the parsed query-string arguments in list context.
With the $key argument, in scalar context this method fetches the first matching query-string arg. In list context it returns all matching args.
See also "query" for the equivalent, but using Apache2::API::Query instead of "args" in APR::Body
See also "query_string" to set or get the query string as a string.
args_status
my $int = $req->args_status; # should be 0
Returns the final status code of the query-string parser.
as_string
Returns the HTTP request as a string by calling "as_string" in Apache2::RequestUtil
auth
Returns the Authorization
header value if any. This ill have been processed upon object initiation phase.
auth_headers
$req->auth_headers;
Setup the output headers so that the client knows how to authenticate itself the next time, if an authentication request failed. This function works only for basic and digest authentication, by calling "note_auth_failure" in Apache2::Access
This method requires AuthType
to be set to Basic
or Digest
. Depending on the setting it will call either "auth_headers_basic" or "auth_headers_digest".
It does not return anything.
auth_headers_basic
$req->auth_headers_basic;
Setup the output headers so that the client knows how to authenticate itself the next time, if an authentication request failed. This function works only for basic authentication.
It does not return anything.
auth_headers_digest
$req->auth_headers_digest;
Setup the output headers so that the client knows how to authenticate itself the next time, if an authentication request failed. This function works only for digest authentication.
It does not return anything.
auth_name
my $auth_name = $req->auth_name();
my $auth_name = $req->auth_name( $new_auth_name );
Sets or gets the current Authorization realm, i.e. the per directory configuration directive AuthName
The AuthName
directive creates protection realm within the server document space. To quote RFC 1945 "These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database."
The client uses the root URL of the server to determine which authentication credentials to send with each HTTP request. These credentials are tagged with the name of the authentication realm that created them. Then during the authentication stage the server uses the current authentication realm, from auth_name
, to determine which set of credentials to authenticate.
auth_type
my $auth_type = $req->auth_type();
my $auth_type = $req->auth_type( $new_auth_type );
Sets or gets the type of authorization required for this request, i.e. the per directory configuration directive AuthType
Normally AuthType
would be set to Basic
to use the basic authentication scheme defined in RFC 1945, Hypertext Transfer Protocol (HTTP/1.0). However, you could set to something else and implement your own authentication scheme.
authorization
Returns the HTTP authorization
header value. This is similar to "auth".
See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
auth_type
Returns the authentication type by calling "auth_type" in Apache2::RequestRec
my $auth_type = $req->auth_type; # Basic
auto_header
Given a boolean value, this enables the auto header or not by calling the method "assbackwards" in Apache2::RequestRec
If this is disabled, you need to make sure to manually update the counter, such as:
$req->connection->keepalives( $req->connection->keepalives + 1 );
See Apache2::RequestRec for more information on this.
basic_auth_passwd
my( $rc, $passwd ) = $req->basic_auth_pw;
Get the details from the basic authentication, by calling "get_basic_auth_pw" in Apache2::Access
It returns:
- 1. the value of an Apache constant
-
This would be
Apache2::Const::OK
if the password value is set (and assured a correct value in "user"); otherwise it returns an error code, eitherApache2::Const::HTTP_INTERNAL_SERVER_ERROR
if things are really confused,Apache2::Const::HTTP_UNAUTHORIZED
if no authentication at all seemed to be in use, orApache2::Const::DECLINED
if there was authentication, but it was notBasic
(in which case, the handler should presumably decline as well). - 2. the password as set in the headers (decoded)
Note that if AuthType
is not set, "get_basic_auth_pw" in Apache2::Access first sets it to Basic
.
body
Returns an APR::Request::Param::Table object containing the POST
data parameters of the Apache2::Request object.
my $body = $req->body;
my @body_names = $req->body;
If there is no request body, then this would return undef
. So, for example, if you do a POST
query without any content, this would return undef
An optional name parameter can be passed to return the POST (or other similar query types) data parameter associated with the given name:
my $foo_body = $req->body("foo");
In scalar context this method fetches the first matching body param. In list context it returns all matching body params.
This is similar to the param
method. The main difference is that modifications to the scalar $req->body()
table affect the underlying apr_table_t
attribute in apreq_request_t
, so their impact will be noticed by all libapreq2
applications during this request.
Contrary to perl hash, this uses APR::Table and the order in the hash is preserved, so you could do:
my @body_names = $req->body;
my @body_names = %$body;
would yield the same thing.
This will throw an APR::Request::Error object whenever "body_status" returns a non-zero value.
Check Apache2::Request and APR::Table for more information.
body_status
my $int = $req->body_status; # should return 0
Returns the final status code of the body parser.
brigade_limit
my $int = $req->brigade_limit;
$req->brigade_limit( $int );
Get or set the brigade_limit for the current parser. This limit determines how many bytes of a file upload that the parser may spool into main memory. Uploads exceeding this limit are written directly to disk.
See also "temp_dir"
call
Provided with an Apache2 API method name, and optionally with some additional arguments, and this will call that Apache2 method and return its result.
This is designed to allow you to call arbitrary Apache2 method that, possibly, are not covered here.
For example:
my $bitmask = $req->call( 'allow_override_opts' );
It returns whatever value this call returns.
charset
Returns the charset, if any, found in the HTTP request received and processed upon initialisation of this module object.
So for example, if the HTTP request Content-type
is
Content-Type: application/json; charset=utf-8
Then, "charset" would return utf-8
See also "type" to retrieve only the content type, i.e without other information such as charset.
See also "client_api_version" which would contain the requested api version, if any.
See also charset for the charset provided, if any. For example utf-8
checkonly
This is also an object initialisation property.
If true, this will discard the normal processing of incoming HTTP request under modperl.
This is useful and intended when testing this module offline.
child_terminate
Terminate the current worker process as soon as the current request is over, by calling "child_terminate" in Apache2::RequestRec
This is not supported in threaded MPMs.
See Apache2::RequestUtil for more information.
client_api_version
Returns the client api version requested, if provided. This is set during the object initialisation phase.
An example header to require api version 1.0
would be:
Accept: application/json; version=1.0; charset=utf-8
In this case, this would return 1.0
close
This close the client connection, by calling "socket" in Apache2::Connection, which returns a APR::Socket
This is not implemented in by APR::Socket, so this is an efficient work around.
If the socket is writable, it is closed and returns the value from closing it, otherwise returns 0
However, a word of caution, you most likely do not need or want to close manually the client connection and instea have your method return Apache2::Const::OK or any other constant matching the HTTP code you want to return.
code
Sets or gets the response status code, by calling "status" in Apache2::RequestRec
From the Apache2::RequestRec documentation:
Usually you will set this value indirectly by returning the status code as the handler's function result. However, there are rare instances when you want to trick Apache into thinking that the module returned an Apache2::Const::OK
status code, but actually send the browser a non-OK status. This may come handy when implementing an HTTP proxy handler. The proxy handler needs to send to the client, whatever status code the proxied server has returned, while returning Apache2::Const::OK
to Apache. e.g.:
$req->status( $some_code );
return( Apache2::Const::OK );
connection
Returns a Apache2::Connection object.
connection_id
Returns the connection id; unique at any point in time by calling "id" in Apache2::Connection.
See Apache2::Connection for more information.
content
Returns the content of the file specified with $req->filename
. It calls "slurp_filename" in Apache2::RequestRec, but instead of returning a scalar reference, which "slurp_filename" in Apache2::RequestRec does, it returns the data itself.
See "slurp_filename" to get a scalar reference instead.
content_encoding
Returns the value of the Content-Encoding
HTTP response header.
See also "headers"
content_languages
my $array_ref = $req->content_languages();
my $array_ref = $req->content_languages( $array_reference );
Sets or gets the value of the Content-Language
HTTP header, by calling "content_languages" in Apache2::RequestRec
Content languages are string like en
or fr
.
If a new value is provided, it must be an array reference of language codes.
It returns the language codes as an array reference.
content_length
Returns the length in byte of the request body, by getting the header Content-Length
value.
See also "headers"
content_type
Retrieves the value of the Content-type
header value. See Apache2::RequestRec for more information.
For example:
application/json; charset=utf-8
See also "type" to retrieve only the content type, i.e without other information such as charset.
See also "client_api_version" which would contain the requested api version, if any.
See also charset for the charset provided, if any. For example utf-8
cookie
Returns the current value for the given cookie name, which may be undef
if nothing is found.
This works by calling the "cookies" method, which returns a cookie jar object.
cookies
Returns a Cookie::Jar object acting as a jar with various methods to access, manipulate and create cookies.
data
This method reads the data sent by the client. It takes an optional hash or hash reference of the following options:
max_size
The maximum size of the data that can be transmitted to us over HTTP. By default, there is no limit.
Finally, if a charset is specified, this will also decode it from its encoded charset into perl internal utf8.
This is specifically designed for JSON
payload.
It returns a string of data upon success, or sets an error and return undef
or an empty list depending on the context.
You can also set a maximum size to read by setting the attribute PAYLOAD_MAX_SIZE
in Apache configuration file.
For example:
<Directory /home/john/www>
PerlOptions +GlobalRequest
SetHandler modperl
# package inheriting from Apache2::API
PerlResponseHandler My::API
# 2Mb upload limit
PerlSetVar PAYLOAD_MAX_SIZE 2097152
</Directory>
This is just an example and not a recommandation. Your mileage may vary.
datetime
Returns a new Apache2::API::DateTime object, which is used to parse and format dates for HTTP.
See "parse_datetime" in Apache2::API and "format_datetime" in Apache2::API
decode
Given a url-encoded string, this returns the decoded string, by calling "decode" in APR::Request
This uses APR::Request XS method.
See also rfc3986
discard_request_body
my $rc = $req->discard_request_body;
In HTTP/1.1
, any method can have a body. However, most GET
handlers would not know what to do with a request body if they received one. This helper routine tests for and reads any message body in the request, simply discarding whatever it receives. We need to do this because failing to read the request body would cause it to be interpreted as the next request on a persistent connection.
Returns Apache2::Const::OK
upon success.
use Apache2::API;
my $rc = $req->discard_request_body;
return( $rc ) if( $rc != Apache2::Const::OK );
This method calls "discard_request_body" in Apache2::RequestIO
dnt
Sets or gets the environment variable HTTP_DNT
using "subprocess_env" in Apache2::RequestRec. See "env" below for more on that.
This is an abbreviation for Do not track
If available, typical value is a boolean such as 0
or 1
document_root
Sets or retrieve the document root for this server.
If a value is provided, it sets the document root to a new value only for the duration of the current request.
See Apache2::RequestUtil for more information.
document_uri
Get the value for the environment variable DOCUMENT_URI
.
encode
Given a string, this returns its url-encoded version
This uses APR::Request XS method.
env
my $val = $req->env( $name );
$req->env( $name, $value );
Using the Apache subprocess_env
table, this sets or gets environment variables. This is the equivalent of this:
$req->subprocess_env;
$env_table = $req->subprocess_env;
$req->subprocess_env( $key => $val );
$val = $req->subprocess_env( $key );
where $req
is this module object.
If one argument is provided, it will return the corresponding environment value.
If one or more sets of key-value pair are provided, they are set accordingly.
If nothing is provided, it returns a APR::Table object.
err_headers_out
Get or sets HTTP response headers, which are printed out even on errors and persist across internal redirects.
According to the Apache2::RequestRec documentation:
The difference between "headers_out" ("headers_out" in Apache2::RequestRec) and "err_headers_out" ("err_headers_out" in Apache2::RequestRec), is that the latter are printed even on error, and persist across internal redirects (so the headers printed for ErrorDocument
handlers will have them).
For example, if a handler wants to return a 404
response, but nevertheless to set a cookie, it has to be:
$req->err_headers_out->add( 'Set-Cookie' => $cookie );
return( Apache2::Const::NOT_FOUND );
If the handler does:
$req->headers_out->add( 'Set-Cookie' => $cookie );
return( Apache2::Const::NOT_FOUND );
the Set-Cookie
header will not be sent.
See Apache2::RequestRec for more information.
filename
Get or sets the filename (full file path) on disk corresponding to this request or response, by calling "filename" in Apache2::RequestRec
See "filename" in Apache2::RequestRec for more information.
finfo
Get and set the finfo request record member, by calling "finfo" in Apache2::RequestRec
See "finfo" in Apache2::RequestRec for more information.
gateway_interface
Sets or gets the environment variable GATEWAY_INTERFACE
using "env"
Typical value returned from the environment variable GATEWAY_INTERFACE
is CGI/1.1
get_handlers
Returns a reference to a list of handlers enabled for a given phase.
$handlers_list = $req->get_handlers( $hook_name );
Example, a list of handlers configured to run at the response phase:
my @handlers = @{ $req->get_handlers('PerlResponseHandler') || [] };
get_status_line
Return the Status-Line
for a given status code (excluding the HTTP-Version field), by calling "status_line" in Apache2::RequestRec
For example:
print( $req->get_status_line( 400 ) );
will print:
400 Bad Request
See also "status_line"
global_request
Returns the Apache2::RequestRec object made global with the proper directive in the Apache VirtualHost configuration.
This calls "request" in Apache2::RequestUtil to retrieve this value.
For example:
<Location /some/where/>
SetHandler perl-script
PerlOptions +GlobalRequest
# ...
</Location>
See also https://perl.apache.org/docs/2.0/user/config/config.html#C_GlobalRequest_
has_auth
my $need_auth = $r->has_auth;
Check if any authentication is required for the current request, by calling "some_auth_required" in Apache2::Access
It returns a boolean value.
See also "is_auth_required", which is an alias of this method.
headers
Gets or sets the HTTP request headers using APR::Table by calling "Apache2::RequestRec/headers_in"
This takes zero, one or sets or key => value
pairs.
When no argument is provided, this returns the APR::Object.
When one argument is provided, it returns the corresponding HTTP header value, if any.
You can set multiple key-value pairs, like so:
$req->headers( $var1 => $val1, $var2 => $val2 );
If a value provided is undef
, it will remove the corresponding HTTP headers.
With the APR::Table object, you can access and set header fields directly, such as:
my $accept = $req->headers->{Accept};
$req->headers->{Accept} = 'application/json';
$req->headers->{Accept} = undef; # unset it
or
my $accept = $req->headers->get( 'Accept' );
$req->headers->set( Accept => 'application/json' );
$req->headers->unset( 'Accept' );
$req->headers->add( Vary => 'Accept-Encoding' );
# Very useful for this header
$req->headers->merge( Vary => 'Accept-Encoding' );
# Empty the headers
$req->headers->clear;
use APR::Const qw( :table );
# to merge: multiple values for the same key are flattened into a comma-separated list.
$req->headers->compress( APR::Const::OVERLAP_TABLES_MERGE );
# to overwrite: each key will be set to the last value seen for that key.
$req->headers->compress( APR::Const::OVERLAP_TABLES_SET );
my $table = $req->headers->copy( $req2->pool );
my $headers = $req->headers;
$req->headers->do(sub
{
my( $key, $val ) = @_;
# Do something
# return(0) to abort
}, keys( %$headers ) );
# or without any filter keys
$req->headers->do(sub
{
my( $key, $val ) = @_;
# Do something
# return(0) to abort
});
# To prepare a table of 20 elements, but the table can still grow
my $table = APR::Table::make( $req->pool, 20 );
my $table2 = $req2->headers;
# overwrite any existing keys in our table $table
$table->overlap( $table2, APR::Const::OVERLAP_TABLES_SET );
# key, value pairs are added, regardless of whether there is another element with the same key in $table
$table->overlap( $table2, APR::Const::OVERLAP_TABLES_MERGE );
my $table3 = $table->overlay( $table2, $pool3 );
See APR::Table for more information.
header_only
This is the same as "is_header_only"
headers_as_hashref
Returns the list of headers as an hash reference, by calling "headers_in" in Apache2::RequestRec
Since the call to Apache2::RequestRec returns a APR::Table object, we may get 2 or more same key name, and in that case, the hash with that key will have as a value an array reference.
headers_as_json
Returns the list of headers as a json data, by retrieving the hash from "headers_as_hashref" and encode it with JSON
headers_in
Returns the list of the headers as special hash, which is actually an APR::Table object.
If a header name is provided, you can retrieve its value like so:
my $cookie = $req->headers_in->{Cookie} || '';
headers_out
This is identical to "headers_in", as it returns a APR::Table object.
Returns or sets the key => value pairs of outgoing HTTP headers, only on 2xx responses.
See also "err_headers_out", which allows to set headers for non-2xx responses and persist across internal redirects.
More information at "headers_out" in Apache2::RequestRec
hostname
Retrieve or set the HTTP server host name, such as www.example.com
, by calling "hostname" in Apache2::RequestRec
This is not the machine hostname.
More information at Apache2::RequestRec
http_host
Returns an URI
object of the HTTP host being accessed. This is created during object initiation phase.
This calls the method host
on the URI object returned by "uri"
id
Returns the connection id; unique at any point in time, by calling "id" in Apache2::Connection.
See Apache2::Connection for more information.
This is the same as "connection_id"
if_modified_since
Returns the value of the HTTP header If-Modified-Since as a DateTime
object.
If no such header exists, it returns undef
or an empty list depending on the context.
if_none_match
Sets or gets the value of the HTTP header If-None-Match
See also "headers"
input_filters
Get or sets the first filter in a linked list of request level input filters. It returns a Apache2::Filter object.
$input_filters = $req->input_filters();
$prev_input_filters = $req->input_filters( $new_input_filters );
According to the Apache2::RequestRec documentation:
For example instead of using $req->read()
to read the POST
data, one could use an explicit walk through incoming bucket brigades to get that data. The following function read_post()
does just that (in fact that's what $req->read()
does behind the scenes):
use APR::Brigade ();
use APR::Bucket ();
use Apache2::Filter ();
use Apache2::Const -compile => qw( MODE_READBYTES );
use APR::Const -compile => qw( SUCCESS BLOCK_READ );
use constant IOBUFSIZE => 8192;
sub read_post {
my $r = shift;
my $bb = APR::Brigade->new( $req->pool,
$req->connection->bucket_alloc );
my $data = '';
my $seen_eos = 0;
do {
$req->input_filters->get_brigade( $bb, Apache2::Const::MODE_READBYTES,
APR::Const::BLOCK_READ, IOBUFSIZE );
for (my $b = $bb->first; $b; $b = $bb->next( $b )) {
if ($b->is_eos) {
$seen_eos++;
last;
}
if ($b->read(my $buf)) {
$data .= $buf;
}
$b->remove; # optimization to reuse memory
}
} while (!$seen_eos);
$bb->destroy;
return $data;
}
As you can see $req->input_filters
gives us a pointer to the last of the top of the incoming filters stack.
is_auth_required
my $need_auth = $r->is_auth_required;
Check if any authentication is required for the current request, by calling "some_auth_required" in Apache2::Access
It returns a boolean value.
See also "has_auth", which is an alias of this method.
is_header_only
Returns a boolean value on whether the request is a HEAD
request or not, by calling "header_only" in Apache2::RequestRec
So, it returns true if the client is asking for headers only, false otherwise.
is_perl_option_enabled
Sets or gets whether a directory level PerlOptions
flag is enabled or not. This returns a boolean value, by calling "is_perl_option_enabled" in Apache2::RequestUtil
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:
$req->subprocess_env unless $req->is_perl_option_enabled('SetupEnv');
See also: PerlOptions and the equivalent function for server level PerlOptions flags.
See the Apache2::RequestUtil module documentation for more information.
is_secure
Returns true (1) if the connection is made under ssl, i.e. of the environment variable HTTPS
is set to on
, other it returns false (0).
This is done by checking if the environment variable HTTPS
is set to on
or not.
json
Returns a JSON object with the relaxed
attribute enabled so that it allows more relaxed JSON
data.
You can provide an optional hash or hash reference of properties to enable or disable:
my $J = $api->json( pretty => 1, relaxed => 1 );
Each property corresponds to one that is supported by JSON
It also supports ordered
, order
and sort
as an alias to canonical
keepalive
$status = $c->keepalive();
$status = $c->keepalive($new_status);
This method answers the question: Should the the connection be kept alive for another HTTP request after the current request is completed?
This sets or gets the status by calling "keepalive" in Apache2::Connection
use Apache2::Const -compile => qw(:conn_keepalive);
# ...
my $c = $req->connection;
if ($c->keepalive == Apache2::Const::CONN_KEEPALIVE) {
# do something
}
elsif ($c->keepalive == Apache2::Const::CONN_CLOSE) {
# do something else
}
elsif ($c->keepalive == Apache2::Const::CONN_UNKNOWN) {
# do yet something else
}
else {
# die "unknown state";
}
Notice that new states could be added later by Apache, so your code should make no assumptions and do things only if the desired state matches.
The method does not return true or false, but one of the states which can be compared against Apache constants (:conn_keepalive constants
).
See Apache2::Connection for more information.
keepalives
my $served = $req->connection->keepalives();
my $served = $req->connection->keepalives( $new_served );
This returns an integer representing how many requests were already served over the current connection.
This method calls "keepalives" in Apache2::Connection
This method is only relevant for keepalive connections. The core connection output filter ap_http_header_filter
increments this value when the response headers are sent and it decides that the connection should not be closed (see "ap_set_keepalive()").
If you send your own set of HTTP headers with $req->assbackwards
, which includes the Keep-Alive
HTTP response header, you must make sure to increment the keepalives
counter.
See Apache2::Connection for more information.
languages
This will check the Accept-Languages
HTTP headers and derive a list of priority ordered user preferred languages and return an array object.
See also the "preferred_language" method.
length
Returns an integer representing the length in bytes of the request body, by calling "bytes_sent" in Apache2::RequestRec
local_addr
Returns our server local address as a APR::SockAddr object, by calling "local_addr" in Apache2::Connection
my $local_sock_addr = $req->connection->local_addr;
my $port = $local_sock_addr->port;
my $ip = $local_sock_addr->ip_get; # e.g.: 192.168.1.2
local_host
Used for ap_get_server_name
when UseCanonicalName
is set to DNS
(ignores setting of HostnameLookups)
This calls "local_host" in Apache2::Connection
Better to use the "server_name" instead.
local_ip
Return our server IP address as string, by calling "local_ip" in Apache2::Connection
location
Get the path of the <Location> section from which the current Perl*Handler
is being called.
This calls "location" in Apache2::RequestUtil
Returns a string.
log_error
Returns the value from "log_error" in Apache2::Request by passing it whatever arguments were received.
main
Get the main request record and returns a Apache2::RequestRec object, by calling "main" in Apache2::RequestRec
If the current request is a sub-request, this method returns a blessed reference to the main request structure. If the current request is the main request, then this method returns undef
.
To figure out whether you are inside a main request or a sub-request/internal redirect, use $req->is_initial_req
.
method
$method = $req->method();
$pre_method = $req->method($new_method);
Get or sets the current request method (e.g. GET
, HEAD
, POST
, etc.), by calling "method" in Apache2::RequestRec
if a new value was passed the previous value is returned.
method_number
my $methnum = $req->method_number();
my $prev_methnum = $req->method_number( $new_methnum );
This sets or gets the client method used, as a number, by calling "method_number" in Apache2::RequestRec
It returns the current method as a number (an Apache2::Const)
For example if the response handler handles only GET
and POST
methods, and not OPTIONS
, it may want to say:
use Apache2::API;
if( $req->method_number == Apache2::Const::M_OPTIONS )
{
$req->allowed( $req->allowed | ( 1 << Apache2::Const::M_GET ) | ( 1 << Apache2::Const::M_POST ) );
return( Apache2::Const::DECLINED );
}
For example, if the module can handle only POST method it could start with:
use Apache2::API;
unless( $req->method_number == Apache2::Const::M_POST )
{
$req->allowed( $req->allowed | ( 1 << Apache2::Const::M_POST ) );
return( Apache2::Const::HTTP_METHOD_NOT_ALLOWED );
}
mod_perl
Returns the value for the environment variable MOD_PERL
.
If a value is provided, it will set the environment variable accordingly.
$req->mod_perl( "mod_perl/2.0.11" );
mod_perl_version
Read-only. This is based on the value returned by "mod_perl".
This returns a version object of the mod perl version being used, so you can call it like:
my $min_version = version->declare( 'v2.0.11' );
if( $req->mod_perl_version >= $min_version )
{
# ok
}
mtime
Last modified time of the requested resource.
Returns a timestamp in second since epoch by calling "mtime" in Apache2::RequestRec
next
Pointer to the redirected request if this is an external redirect.
Returns a Apache2::RequestRec blessed reference to the next (internal) request structure or undef
if there is no next request.
no_cache
Add/remove cache control headers by calling "no_cache" in Apache2::RequestUtil. A true value sets the no_cache
request record member to a true value and inserts:
Pragma: no-cache
Cache-control: no-cache
into the response headers, indicating that the data being returned is volatile and the client should not cache it.
A false value unsets the no_cache
request record member and the mentioned headers if they were previously set.
This method should be invoked before any response data has been sent out.
See Apache2::RequestUtil for more information.
notes
Get or sets text notes for the duration of this request by calling "pnotes" in Apache2::RequestUtil. These notes can be passed from one module to another (not only mod_perl, but modules in any other language).
If a new value was passed, returns the previous value.
The returned value is a APR::Table object by calling "notes" in Apache2::RequestUtil
output_filters
my $output_filters = $req->connection->output_filters();
my $prev_output_filters = $req->output_filters( $new_output_filters );
Set or get the first filter in a linked list of request level output filters by calling "output_filters". It returns a Apache2::Filter object.
If a new output filters was passed, returns the previous value.
According to the Apache2::RequestRec documentation:
For example instead of using $req->print()
to send the response body, one could send the data directly to the first output filter. The following function send_response_body()
does just that:
use APR::Brigade ();
use APR::Bucket ();
use Apache2::Filter ();
sub send_response_body
{
my( $req, $data ) = @_;
my $bb = APR::Brigade->new( $req->pool,
$req->connection->bucket_alloc );
my $b = APR::Bucket->new( $bb->bucket_alloc, $data );
$bb->insert_tail( $b );
$req->output_filters->fflush( $bb );
$bb->destroy;
}
In fact that's what $req->read()
does behind the scenes. But it also knows to parse HTTP headers passed together with the data and it also implements buffering, which the above function does not.
param
Provided a name, this returns its equivalent value, using "param" in Apache2::API::Request::Params.
If $name
is an upload field, ie part of a multipart post data, it returns an Apache2::API::Request::Upload object instead.
If a value is provided, this calls "param" in Apache2::API::Request::Param providing it with the name ane value. This uses APR::Request::Param.
params
Get the request parameters (using case-insensitive keys) by mimicing the OO interface of CGI::param.
It can take as argument, only a key and it will then retrieve the corresponding value, or it can take a key and value pair to set them using "param" in Apache2::API::Request::Params
If the value is an array, this will set multiple entry of the key for each value provided.
This uses Apache APR::Table and works for both POST
and GET
methods.
If the methods received was a GET
method, this method returns the value of the "query" method instead.
parse_date
Alias to "parse_date" in Apache2::API::DateTime
path
Get the value for the environment variable PATH
See also "env"
path_info
my $path_info = $req->path_info();
my $prev_path_info = $req->path_info( $path_info );
Get or set the PATH_INFO
, what is left in the path after the URI --> filename
translation, by calling "path_info" in Apache2::RequestRec
Return a string as the current value.
payload
Returns the JSON data decoded into a perl structure. This is set at object initiation phase and calls the "data" method to read the incoming data and decoded it into perl internal utf8.
per_dir_config
Get the dir config vector, by calling "per_dir_config" in Apache2::RequestRec. Returns a Apache2::ConfVector object.
For an in-depth discussion, refer to the Apache Server Configuration Customization in Perl chapter.
pnotes
Share Perl variables between Perl HTTP handlers, using "pnotes" in Apache2::RequestUtil.
# to share variables by value and not reference, $val should be a lexical.
$old_val = $req->pnotes( $key => $val );
$val = $req->pnotes( $key );
$hash_ref = $req->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;
$req->pnotes( 'v'=> $v ); $req->pnotes->{v} = $v;
$v++; $v++;
my $x = $req->pnotes('v'); my $x = $req->pnotes->{v};
pool
Returns the pool associated with the request as a APR::Pool object of the Apache2 connection. If you rather want access to the pool object of the Apache2 request itself, use "request", such as:
# $rest being a Apache2::API object
my $request_pool = $req->pool;
$request_pool->cleanup_register( \&cleanup );
preferred_language
Given an array reference of supported languages, this method will get the client accepted languages by calling "accept_language" and derive the best match, ie the client preferred language, using HTTP::AcceptLanguage,.
It returns a string representing a language code.
See also: "languages" and "accept_language"
prev
my $prev_r = $req->prev();
Pointer to the previous request if this is an internal redirect, by calling "prev" in Apache2::RequestRec.
Returns a Apache2::RequestRec blessed reference to the previous (internal) request structure or undef
if there is no previous request.
protocol
my $protocol = $req->protocol();
Get a string identifying the protocol that the client speaks, such as HTTP/1.0
or HTTP/1.1
, by calling "protocol" in Apache2::RequestRec
proxyreq
my $status = $req->proxyreq( $val );
Get or set the proxyrec request record member and optionally adjust other related fields, by calling "proxyreq" in Apache2::RequestRec.
Valid values are: PROXYREQ_NONE
, PROXYREQ_PROXY
, PROXYREQ_REVERSE
, PROXYREQ_RESPONSE
According to the Apache2::RequestRec documentation:
For example to turn a normal request into a proxy request to be handled on the same server in the PerlTransHandler
phase run:
my $real_url = $req->unparsed_uri;
$req->proxyreq( Apache2::Const::PROXYREQ_PROXY );
$req->uri( $real_url );
$req->filename( "proxy:$real_url" );
$req->handler( 'proxy-server' );
Also remember that if you want to turn a proxy request into a non-proxy request, it is not enough to call:
$req->proxyreq( Apache2::Const::PROXYREQ_NONE );
You need to adjust $req->uri
and $req->filename
as well if you run that code in PerlPostReadRequestHandler
phase, since if you do not -- mod_proxy
's own post_read_request handler will override your settings (as it will run after the mod_perl handler).
And you may also want to add
$req->set_handlers( PerlResponseHandler => [] );
so that any response handlers which match apache directives will not run in addition to the mod_proxy content handler.
push_handlers
Add one or more handlers to a list of handlers to be called for a given phase, by calling "push_handlers" in Apache2::RequestUtil.
my $ok = $req->push_handlers( $hook_name => \&handler );
my $ok = $req->push_handlers( $hook_name => ['Foo::Bar::handler', \&handler2] );
It returns a true value on success, otherwise a false value
Examples:
A single handler:
$req->push_handlers( PerlResponseHandler => \&handler );
Multiple handlers:
$req->push_handlers( PerlFixupHandler => ['Foo::Bar::handler', \&handler2] );
Anonymous functions:
$req->push_handlers( PerlLogHandler => sub { return Apache2::Const::OK } );
See Apache2::RequestUtil for more information.
query
Check the query string sent in the HTTP request, which obviously should be a GET
, but not necessarily, and parse it with Apache2::API::Query and return an hash reference, by calling Apache2::API::Query
query_string
my $string = $req->args(); # q=hello&lang=ja_JP
my $prev_string = $req->args( $new_string );
Actually calls "args" in Apache2::RequestRec behind the scene.
This sets or gets the request query string.
read
Read data from the client and returns the number of characters actually read.
$cnt = $req->read( $buffer, $len );
$cnt = $req->read( $buffer, $len, $offset );
This method shares a lot of similarities with the Perl core read()
function. The main difference in the error handling, which is done via APR::Error exceptions
See Apache2::RequestIO for more information.
redirect_error_notes
Gets or sets the value for the environment variable REDIRECT_ERROR_NOTES
redirect_query_string
Gets or sets the value for the environment variable REDIRECT_QUERY_STRING
redirect_status
Gets or sets the value for the environment variable REDIRECT_STATUS
redirect_url
Gets or sets the value for the environment variable REQUEST_URI
referer
Returns the value of the HTTP Referer
header, if any.
See also "headers"
remote_addr
Returns the remote host socket address as a APR::SockAddr object.
Because the Apache2 mod_perl api has changed, before the method to call was client_addr
and is now remote_addr
my $remote_sock_addr = $req->remote_addr();
my $local_sock_addr = $req->local_addr();
my $ip = $remote_sock_addr->ip_get; # e.g.: 192.168.1.2
my $port = $soremote_sock_addrck_addr->port;
The above would be the equivalent in conventional perl of:
use Socket 'sockaddr_in';
my( $port, $ip ) = sockaddr_in( getpeername( $remote_sock ) );
See Apache2::Connection for more information.
remote_host
Returns the remote client host name, by calling "get_remote_host" in Apache2::Connection
Calling get_remote_host
is the recommended method over remote_host
If the configuration directive HostNameLookups
is set to off
, this returns the dotted decimal representation of the client's IP address instead. Might return undef
if the hostname is not known.
my $remote_host = $req->remote_host();
my $remote_host = $req->remote_host( $type );
my $remote_host = $req->remote_host( $type, $dir_config );
If $type
is provided, it must be a :remotehost
constant (see Apache2::Const):
Apache2::Const::REMOTE_DOUBLE_REV
-
Will always force a DNS lookup, and also force a double reverse lookup, regardless of the "HostnameLookups" setting. The result is the (double reverse checked) hostname, or
undef
if any of the lookups fail. Apache2::Const::REMOTE_HOST
-
Returns the hostname, or
undef
if the hostname lookup fails. It will force a DNS lookup according to theHostnameLookups
setting. Apache2::Const::REMOTE_NAME
-
Returns the hostname, or the dotted quad if the hostname lookup fails. It will force a DNS lookup according to the
HostnameLookups
setting. Apache2::Const::REMOTE_NOLOOKUP
-
Is like
Apache2::Const::REMOTE_NAME
except that a DNS lookup is never forced.If
$dir_config
is provided, this is the directory config vector from the request. It is needed to find the container in which the directiveHostnameLookups
is set. To get one for the current request use$req->per_dir_config
.By default,
undef
is passed, in which case it is the same as ifHostnameLookups
was set toOff
.
Default value is Apache2::Const::REMOTE_NAME
remote_ip
my $remote_ip = $req->connection->remote_ip();
my $prev_remote_ip = $req->connection->remote_ip( $new_remote_ip );
Sets or gets the ip address of the client, ie remote host making the request, by calling "client_ip" in Apache2::Connection or "remote_ip" in Apache2::Connection
It returns a string representing an ip address,
remote_port
It returns the value for the environment variable REMOTE_PORT
or set its value with the argument provided if any.
$req->remote_port( 51234 );
print( "Remote port is: ", $req->remote_port, "\n" );
request
Returns the embedded Apache2::RequestRec object provided initially at object instantiation.
request_scheme
Gets or sets the environment variable REQUEST_SCHEME
request_time
Read-only.
Returns the time when the request started as a DateTime object with Apache2::API::DateTime as the formatter.
request_uri
This returns the current value for the environment variable REQUEST_URI
, or set its value if an argument is provided.
The uri provided by this environment variable include the path info if any.
For example, assuming you have a cgi residing in /cgi-bin/prog.cgi
and it is called with the path info /some/value
, the value returned would then be /cgi-bin/prog.cgi/some/value
requires
$requires = $req->requires;
Retrieve information about all of the requires directives for this request, by calling "requires" in Apache2::Access
It returns an array reference of hash references, containing information related to the require
directive.
For example if the configuration had the following require directives:
Require user goo bar
Require group bar tar
<Limit POST>
Require valid-user
</Limit>
this method will return the following datastructure:
[
{
method_mask => -1,
requirement => 'user goo bar'
},
{
method_mask => -1,
requirement => 'group bar tar'
},
{
method_mask => 4,
requirement => 'valid-user'
}
];
The requirement field is what was passed to the "Require" directive. The method_mask field is a bitmask which can be modified by the Limit
directive, but normally it can be safely ignored as it's mostly used internally.
See also https://httpd.apache.org/docs/2.4/en/howto/access.html
satisfies
my $satisfy = $req->satisfies;
Get the applicable value of the Satisfy
directive, by calling "satisfies" in Apache2::Access
It returns one of the Apache2::Const :satisfy
constants:
Apache2::Const::SATISFY_ANY
Any of the requirements must be met.
Apache2::Const::SATISFY_ALL
All of the requirements must be met.
Apache2::Const::SATISFY_NOSPEC
There are no applicable
satisfy
lines.
script_filename
This returns the current value for the environment variable SCRIPT_FILENAME
, or set its value if an argument is provided.
For example, if the file being served resides at the uri /about.html
and your document root is /var/www
, the the value returned would be /var/www/about.html
It is noteworthy that this environment variable does not include any path info set, if any.
script_name
This returns the current value for the environment variable SCRIPT_NAME
, or set its value if an argument is provided.
For example, if the file being served resides at the uri /about.html
, the value returned would be /about.html
.
Even though the environment variable name is SCRIPT_NAME
, its value is any file being served and contrary to what you might believe, it is not limited to a script, such as a program.
script_uri
This returns the current value for the environment variable SCRIPT_URI
, or set its value if an argument is provided.
It is similar to "request_uri", except this returns a full uri including the protocol and host name. For example: https://example.com/cgi-bin/prog.cgi/path/info
script_url
This returns the current value for the environment variable SCRIPT_URL
, or set its value if an argument is provided.
The value returned is identical to that of "request_uri", i.e, for example: /cgi-bin/prog.cgi/path/info
server
Get the Apache2::ServerRec object for the server the request $r
is running under.
server_addr
This returns the current value for the environment variable SERVER_ADDR
, or set its value if an argument is provided.
Typical value is an ip address.
server_admin
Returns the server admin as provided by "server_admin" in Apache2::ServerRec
server_hostname
Returns the server host name as provided by "server_hostname" in Apache2::ServerRec
server_name
Get the current request's server name as provided by "get_server_name" in Apache2::RequestUtil
See Apache2::RequestUtil for more information.
server_port
Get the current server port as provided by "get_server_port" in Apache2::RequestUtil
See Apache2::RequestUtil for more information.
server_protocol
This returns the current value for the environment variable SERVER_PROTOCOL
, or set its value if an argument is provided.
Typical value is HTTP/1.1
server_signature
This returns the current value for the environment variable SERVER_SIGNATURE
, or set its value if an argument is provided.
The value of this environment variable can be empty if the Apache configuration parameter ServerSignature
is set to Off
server_software
This returns the current value for the environment variable SERVER_SOFTWARE
, or set its value if an argument is provided.
This is typically something like Apache/2.4.41 (Ubuntu)
server_version
This will endeavour to find out the Apache version.
When called multiple times, it will return a cached value and not recompute each time.
It first tries "get_server_description" in Apache2::ServerUtil
Otherwise, it tries to find the binary apxs
on the filesystem, and if found, calls it like:
apxs -q -v HTTPD_VERSION
If this does not work too, it will try to call the Apache binary (apache2
or httpd
) like:
apache2 -v
and extract the version.
It returns the version found as a version object, or an empty string if nothing could be found.
set_basic_credentials
Provided with a user name and a password, this populates the incoming request headers table (headers_in
) with authentication headers for Basic Authorization as if the client has submitted those in first place:
$req->set_basic_credentials( $username, $password );
See Apache2::RequestUtil for more information.
set_handlers
Set a list of handlers to be called for a given phase. Any previously set handlers are forgotten.
See "set_handlers" in Apache2::RequestUtil for more information.
$ok = $req->set_handlers( $hook_name => \&handler );
$ok = $req->set_handlers( $hook_name => ['Foo::Bar::handler', \&handler2] );
$ok = $req->set_handlers( $hook_name => [] );
$ok = $req->set_handlers( $hook_name => undef );
slurp_filename
Slurp the contents of $req->filename
:
This returns a scalar reference instead of the actual string. To get the string, use "content"
Note that if you assign to $req-
filename> you need to update its stat record.
socket
Get or sets the client socket and returns a APR::Socket object.
This calls "client_socket" in Apache2::Connection package.
status
my $status = $req->status();
my $prev_status = $req->status( $new_status );
Get or set thes reply status for the client request, which is an integer, by calling "status" in Apache2::RequestRec
Normally you would use some Apache2::Const constant, e.g. Apache2::Const::REDIRECT.
From the Apache2::RequestRec documentation:
Usually you will set this value indirectly by returning the status code as the handler's function result. However, there are rare instances when you want to trick Apache into thinking that the module returned an Apache2::Const:OK
status code, but actually send the browser a non-OK status. This may come handy when implementing an HTTP proxy handler. The proxy handler needs to send to the client, whatever status code the proxied server has returned, while returning Apache2::Const::OK to Apache. e.g.:
$req->status( $some_code );
return( Apache2::Const::OK );
See also $req->status_line
, which. if set, overrides $req->status
.
status_line
my $status_line = $req->status_line();
my $prev_status_line = $req->status_line( $new_status_line );
Get or sets the response status line. The status line is a string like 200 Document follows
and it will take precedence over the value specified using the $req->status()
described above.
According to the Apache2::RequestRec documentation:
When discussing $req->status
we have mentioned that sometimes a handler runs to a successful completion, but may need to return a different code, which is the case with the proxy server. Assuming that the proxy handler forwards to the client whatever response the proxied server has sent, it will usually use status_line()
, like so:
$req->status_line( $response->code() . ' ' . $response->message() );
return( Apache2::Const::OK );
In this example $response
could be for example an HTTP::Response object, if LWP::UserAgent was used to implement the proxy.
This method is also handy when you extend the HTTP protocol and add new response codes. For example you could invent a new error code and tell Apache to use that in the response like so:
$req->status_line( "499 We have been FooBared" );
return( Apache2::Const::OK );
Here 499 is the new response code, and We have been FooBared is the custom response message.
str2datetime
Alias to "str2datetime" in Apache2::API::DateTime
str2time
Alias to "str2time" in Apache2::API::DateTime
subnet_of
Provided with an ip address (v4 or v6), and optionally a subnet mask, and this will return a boolean value indicating if the current connection ip address is part of the provided subnet.
The mask can be a string or a number of bits.
It uses APR::IpSubnet and performs the test using the object from APR::SockAddr as provided with "remote_addr"
my $ok = $req->subnet_of( '127.0.0.1' );
my $ok = $req->subnet_of( '::1' );
my $ok = $req->subnet_of( '127.0.0.1', '255.0.0.0' );
my $ok = $req->subnet_of( '127.0.0.1', 15 );
if( !$req->subnet_of( '127.0.0.1' ) )
{
print( "Sorry, only local connections allowed\n" );
}
subprocess_env
Get or sets the Apache2::RequestRec subprocess_env
table, or optionally set the value of a named entry.
From the Apache2::RequestRec documentation:
When called in void context with no arguments, it populate %ENV
with special variables (e.g. $ENV{QUERY_STRING}
) like mod_cgi does.
When called in a non-void context with no arguments, it returns an APR::Table object
.
When the $key argument (string) is passed, it returns the corresponding value (if such exists, or undef
. The following two lines are equivalent:
$val = $req->subprocess_env( $key );
$val = $req->subprocess_env->get( $key );
When the $key and the $val arguments (strings) are passed, the value is set. The following two lines are equivalent:
$req->subprocess_env( $key => $val );
$req->subprocess_env->set( $key => $val );
The subprocess_env
table
is used by Apache2::SubProcess, to pass environment variables to externally spawned processes. It is also used by various Apache modules, and you should use this table to pass the environment variables. For example if in PerlHeaderParserHandler
you do:
$req->subprocess_env( MyLanguage => "de" );
you can then deploy mod_include
and write in .shtml
document:
<!--#if expr="$MyLanguage = en" -->
English
<!--#elif expr="$MyLanguage = de" -->
Deutsch
<!--#else -->
Sorry
<!--#endif -->
temp_dir
my $dir = $req->temp_dir;
$req->temp_dir( $dir );
Get or set the spool directory for uploads which exceed the configured brigade_limit.
the_request
my $request = $req->the_request();
my $old_request = $req->uri( $new_request );
Get or set the first HTTP request header as a string by calling "the_request" in Apache2::RequestRec. For example:
GET /foo/bar/my_path_info?args=3 HTTP/1.0
time2datetime
Alias to "time2datetime" in Apache2::API::DateTime
time2str
Alias to "time2str" in Apache2::API::DateTime
type
Returns the content type of the request received. This value is set at object initiation phase.
So for example, if the HTTP request Content-type
is
Content-Type: application/json; charset=utf-8
Then, "type" would return application/json
unparsed_uri
The URI without any parsing performed.
If for example the request was:
GET /foo/bar/my_path_info?args=3 HTTP/1.0
$req->uri
returns:
/foo/bar/my_path_info
whereas $req->unparsed_uri
returns:
/foo/bar/my_path_info?args=3
uploads
Returns an array object of Apache2::API::Request::Upload objects.
uri
Returns a URI object representing the full uri of the request.
This is different from the original Apache2::RequestRec which only returns the path portion of the URI.
So, to get the path portion using our "uri" method, one would simply do $req->uri->path()
This URI object is built using "get_server_name" in Apache2::RequestUtil for the host
, "get_server_port" in Apache2::RequestUtil for the port number, and the scheme is https
if the port is 443
, otherwise http
. It is followed then by the path build by calling "unparsed_uri" in Apache2::RequestRec
url_decode
This is merely a convenient pointer to "decode"
url_encode
This is merely a convenient pointer to "encode"
user
Get the user name, if an authentication process was successful. Or set it, by calling "user" in Apache2::RequestRec
For example, let's print the username passed by the client:
my( $res, $sent_pw ) = $req->get_basic_auth_pw;
return( $res ) if( $res != Apache2::Const::OK );
print( "User: ", $req->user );
user_agent
Returns the user agent, ie the browser signature as provided in the request headers received under the HTTP header User-Agent
_find_bin( string )
Given a binary, this will search for it in the path.
_try( object type, method name, @_ )
Given an object type, a method name and optional parameters, this attempts to call it.
Apache2 methods are designed to die upon error, whereas our model is based on returning undef
and setting an exception with Module::Generic::Exception, because we believe that only the main program should be in control of the flow and decide whether to interrupt abruptly the execution, not some sub routines.
AUTHOR
Jacques Deguest <jack@deguest.jp>
SEE ALSO
Apache2::Request, Apache2::RequestRec, Apache2::RequestUtil
COPYRIGHT & LICENSE
Copyright (c) 2023 DEGUEST Pte. Ltd.
You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.