The following methods can be called on the CGI::Tiny object provided to the "cgi" block.
Setupset_error_handler
$cgi = $cgi->set_error_handler(sub {
my ($cgi, $error, $rendered) = @_;
...
});
Sets an error handler to run in the event of an exception or if the script ends without rendering a
response. The handler will be called with the CGI::Tiny object, the error value, and a boolean indicating
whether response headers have been rendered yet.
The error value can be any exception thrown by Perl or user code. It should generally not be included in
any response rendered to the client, but instead warned or logged.
Exceptions may occur before or after response headers have been rendered. If response headers have not
been rendered, error handlers may inspect "response_status_code" and/or render some error response. The
response status code will be set to 500 when this handler is called if it has not been set to a specific
400- or 500-level error status.
If the error handler itself throws an exception, that error and the original error will be emitted as a
warning. If no response has been rendered after the error handler completes or dies, a default error
response will be rendered.
NOTE: The error handler is only meant for logging and customization of the final error response in a
failed request dispatch; to handle exceptions within standard application flow without causing an error
response, use an exception handling mechanism such as Syntax::Keyword::Try or Feature::Compat::Try (which
will use the new "try" feature if available).
set_request_body_buffer
$cgi = $cgi->set_request_body_buffer(256*1024);
Sets the buffer size (number of bytes to read at once) for reading the request body. Defaults to the
value of the "CGI_TINY_REQUEST_BODY_BUFFER" environment variable or 262144 (256 KiB). A value of 0 will
use the default value.
set_request_body_limit
$cgi = $cgi->set_request_body_limit(16*1024*1024);
Sets the limit in bytes for the request body. Defaults to the value of the "CGI_TINY_REQUEST_BODY_LIMIT"
environment variable or 16777216 (16 MiB). A value of 0 will remove the limit (not recommended unless you
have other safeguards on memory usage).
Since the request body is not parsed until needed, methods that parse the request body like "body" or
"upload" will set the response status to "413 Payload Too Large" and throw an exception if the content
length is over the limit. Files uploaded through a "multipart/form-data" request body also count toward
this limit, though they are streamed to temporary files when parsed.
set_multipart_form_options
$cgi = $cgi->set_multipart_form_options({discard_files => 1, tempfile_args => [SUFFIX => '.dat']});
Set a hash reference of options to pass when parsing a "multipart/form-data" request body with
"parse_multipart_form_data" in CGI::Tiny::Multipart. No effect after the form data has been parsed such
as by calling "body_params" or "uploads" for the first time.
NOTE: Options like "parse_as_files" and "on_file_buffer" can alter the "content" and "file" keys of the
form field structure returned by "body_parts". Thus "uploads" may not contain "file" and may instead
contain "content", and "body_params" text field values may be read from "file", which will be expected to
be a seekable filehandle if present.
set_multipart_form_charset
$cgi = $cgi->set_multipart_form_charset('UTF-8');
Sets the default charset for decoding "multipart/form-data" forms, defaults to "UTF-8". Parameter and
upload field names, upload filenames, and text parameter values that don't specify a charset will be
decoded from this charset. Set to an empty string to disable this decoding, effectively interpreting such
values in "ISO-8859-1".
set_input_handle
$cgi = $cgi->set_input_handle($fh);
Sets the input handle to read the request body from. If not set, reads from "STDIN". The handle will have
"binmode" applied before reading to remove any translation layers.
set_output_handle
$cgi = $cgi->set_output_handle($fh);
Sets the output handle to print the response to. If not set, prints to "STDOUT". The handle will have
"binmode" applied before printing to remove any translation layers.
RequestEnvironment
CGI::Tiny provides direct access to CGI request meta-variables
<https://tools.ietf.org/html/rfc3875#section-4.1> via methods that map to the equivalent uppercase names
(and a few short aliases). Since CGI does not distinguish between missing and empty values, missing
values will be normalized to an empty string.
auth_type
# AUTH_TYPE="Basic"
my $auth_type = $cgi->auth_type;
The authentication scheme used in the "Authorization" HTTP request header if any.
content_length
# CONTENT_LENGTH="42"
my $content_length = $cgi->content_length;
The size in bytes of the request body content if any.
content_type
# CONTENT_TYPE="text/plain;charset=UTF-8"
my $content_type = $cgi->content_type;
The MIME type of the request body content if any.
gateway_interface
# GATEWAY_INTERFACE="CGI/1.1"
my $gateway_inteface = $cgi->gateway_interface;
The CGI version used for communication with the CGI server.
path_infopath
# PATH_INFO="/foo/42"
my $path = $cgi->path_info;
my $path = $cgi->path;
The URL path following the "SCRIPT_NAME" in the request URL if any.
path_translated
# PATH_TRANSLATED="/var/www/html/foo/42"
my $path_translated = $cgi->path_translated;
A local file path derived from "PATH_INFO" by the CGI server, as if it were a request to the document
root, if it chooses to provide it.
query_stringquery
# QUERY_STRING="foo=bar"
my $query = $cgi->query_string;
my $query = $cgi->query;
The query string component of the request URL.
remote_addr
# REMOTE_ADDR="8.8.8.8"
my $remote_addr = $cgi->remote_addr;
The IPv4 or IPv6 address of the requesting client.
remote_host
# REMOTE_HOST="example.com"
my $remote_host = $cgi->remote_host;
The domain name of the requesting client if available, or "REMOTE_ADDR".
remote_ident
# REMOTE_IDENT="someuser"
my $remote_ident = $cgi->remote_ident;
The identity of the client reported by an RFC 1413 ident request if available.
remote_user
# REMOTE_USER="someuser"
my $remote_user = $cgi->remote_user;
The user identity provided as part of an "AUTH_TYPE" authenticated request.
request_methodmethod
# REQUEST_METHOD="GET"
my $method = $cgi->request_method;
my $method = $cgi->method;
The HTTP request method verb.
script_name
# SCRIPT_NAME="/cgi-bin/script.cgi"
my $script_name = $cgi->script_name;
The host-relative URL path to the CGI script.
server_name
# SERVER_NAME="example.com"
my $server_name = $cgi->server_name;
The hostname of the server as the target of the request, such as from the "Host" HTTP request header.
server_port
# SERVER_PORT="443"
my $server_port = $cgi->server_port;
The TCP port on which the server received the request.
server_protocol
# SERVER_PROTOCOL="HTTP/1.1"
my $server_protocol = $cgi->server_protocol;
The HTTP protocol version of the request.
server_software
# SERVER_SOFTWARE="Apache\/2.4.37 (centos)"
my $server_software = $cgi->server_software;
The name and version of the CGI server.
RequestParsingheaders
my $hashref = $cgi->headers;
Hash reference of available request header names and values. Header names are represented in lowercase.
header
my $value = $cgi->header('Accept-Language');
Retrieve the value of a request header by name (case insensitive). CGI request headers can only contain a
single value, which may be combined from multiple values.
cookies
my $pairs = $cgi->cookies;
Retrieve request cookies as an ordered array reference of name/value pairs, represented as two-element
array references.
cookie_names
my $arrayref = $cgi->cookie_names;
Retrieve request cookie names as an ordered array reference, without duplication.
cookie
my $value = $cgi->cookie('foo');
Retrieve the value of a request cookie by name. If multiple cookies were passed with the same name,
returns the last value. Use "cookie_array" to get multiple values of a cookie name.
cookie_array
my $arrayref = $cgi->cookie_array('foo');
Retrieve values of a request cookie name as an ordered array reference.
params
my $pairs = $cgi->params;
Retrieve URL query string parameters and "application/x-www-form-urlencoded" or "multipart/form-data"
body parameters as an ordered array reference of name/value pairs, represented as two-element array
references. Names and values are decoded to Unicode characters.
Query parameters are returned first, followed by body parameters. Use "query_params" or "body_params" to
retrieve query or body parameters separately.
NOTE: This will read the text form fields into memory as in "body_params".
param_names
my $arrayref = $cgi->param_names;
Retrieve URL query string parameter names and "application/x-www-form-urlencoded" or
"multipart/form-data" body parameter names, decoded to Unicode characters, as an ordered array reference,
without duplication.
Query parameter names are returned first, followed by body parameter names. Use "query_param_names" or
"body_param_names" to retrieve query or body parameter names separately.
NOTE: This will read the text form fields into memory as in "body_params".
param
my $value = $cgi->param('foo');
Retrieve value of a named URL query string parameter or "application/x-www-form-urlencoded" or
"multipart/form-data" body parameter, decoded to Unicode characters.
If the parameter name was passed multiple times, returns the last body parameter value if any, otherwise
the last query parameter value. Use "param_array" to get multiple values of a parameter, or "query_param"
or "body_param" to retrieve the last query or body parameter value specifically.
NOTE: This will read the text form fields into memory as in "body_params".
param_array
my $arrayref = $cgi->param_array('foo');
Retrieve values of a named URL query string parameter or "application/x-www-form-urlencoded" or
"multipart/form-data" body parameter, decoded to Unicode characters, as an ordered array reference.
Query parameter values will be returned first, followed by body parameter values. Use "query_param_array"
or "body_param_array" to retrieve query or body parameter values separately.
NOTE: This will read the text form fields into memory as in "body_params".
query_params
my $pairs = $cgi->query_params;
Retrieve URL query string parameters as an ordered array reference of name/value pairs, represented as
two-element array references. Names and values are decoded to Unicode characters.
query_param_names
my $arrayref = $cgi->query_param_names;
Retrieve URL query string parameter names, decoded to Unicode characters, as an ordered array reference,
without duplication.
query_param
my $value = $cgi->query_param('foo');
Retrieve value of a named URL query string parameter, decoded to Unicode characters.
If the parameter name was passed multiple times, returns the last value. Use "query_param_array" to get
multiple values of a parameter.
query_param_array
my $arrayref = $cgi->query_param_array('foo');
Retrieve values of a named URL query string parameter, decoded to Unicode characters, as an ordered array
reference.
body
my $bytes = $cgi->body;
Retrieve the request body as bytes.
NOTE: This will read the whole request body into memory, so make sure the "set_request_body_limit" can
fit well within the available memory.
Not available after calling "body_parts", "body_params", or "uploads" (or related accessors) on a
"multipart/form-data" request, since this type of request body is not retained in memory after parsing.
body_json
my $data = $cgi->body_json;
Decode an "application/json" request body from UTF-8-encoded JSON.
NOTE: This will read the whole request body into memory, so make sure the "set_request_body_limit" can
fit well within the available memory.
body_params
my $pairs = $cgi->body_params;
Retrieve "application/x-www-form-urlencoded" or "multipart/form-data" body parameters as an ordered array
reference of name/value pairs, represented as two-element array references. Names and values are decoded
to Unicode characters.
NOTE: This will read the text form fields into memory, so make sure the "set_request_body_limit" can fit
well within the available memory. "multipart/form-data" file uploads will be streamed to temporary files
accessible via "uploads" and related methods.
body_param_names
my $arrayref = $cgi->body_param_names;
Retrieve "application/x-www-form-urlencoded" or "multipart/form-data" body parameter names, decoded to
Unicode characters, as an ordered array reference, without duplication.
NOTE: This will read the text form fields into memory as in "body_params".
body_param
my $value = $cgi->body_param('foo');
Retrieve value of a named "application/x-www-form-urlencoded" or "multipart/form-data" body parameter,
decoded to Unicode characters.
If the parameter name was passed multiple times, returns the last value. Use "body_param_array" to get
multiple values of a parameter.
NOTE: This will read the text form fields into memory as in "body_params".
body_param_array
my $arrayref = $cgi->body_param_array('foo');
Retrieve values of a named "application/x-www-form-urlencoded" or "multipart/form-data" body parameter,
decoded to Unicode characters, as an ordered array reference.
NOTE: This will read the text form fields into memory as in "body_params".
body_parts
my $parts = $cgi->body_parts;
Retrieve "multipart/form-data" request body parts as an ordered array reference using
"parse_multipart_form_data" in CGI::Tiny::Multipart. Most applications should retrieve multipart form
data through "body_params" and "uploads" (or related accessors) instead.
NOTE: This will read the text form fields into memory, so make sure the "set_request_body_limit" can fit
well within the available memory. File uploads will be streamed to temporary files.
uploads
my $pairs = $cgi->uploads;
Retrieve "multipart/form-data" file uploads as an ordered array reference of name/upload pairs,
represented as two-element array references. Names are decoded to Unicode characters.
NOTE: This will read the text form fields into memory, so make sure the "set_request_body_limit" can fit
well within the available memory.
File uploads are represented as a hash reference containing the following keys:
filename
Original filename supplied to file input. An empty filename may indicate that no file was submitted.
content_type
"Content-Type" of uploaded file, undef if unspecified.
size
File size in bytes.
file
File::Temp object storing the file contents in a temporary file, which will be cleaned up when the
CGI script ends by default. The filehandle will be open with the "seek" pointer at the start of the
file for reading.
upload_names
my $arrayref = $cgi->upload_names;
Retrieve "multipart/form-data" file upload names, decoded to Unicode characters, as an ordered array
reference, without duplication.
NOTE: This will read the text form fields into memory as in "uploads".
upload
my $upload = $cgi->upload('foo');
Retrieve a named "multipart/form-data" file upload. If the upload name was passed multiple times, returns
the last value. Use "upload_array" to get multiple uploads with the same name.
See "uploads" for details on the representation of the upload.
NOTE: This will read the text form fields into memory as in "uploads".
upload_array
my $arrayref = $cgi->upload_array('foo');
Retrieve all "multipart/form-data" file uploads of the specified name as an ordered array reference.
See "uploads" for details on the representation of the uploads.
NOTE: This will read the text form fields into memory as in "uploads".
Responseset_nph
$cgi = $cgi->set_nph;
$cgi = $cgi->set_nph(1);
If set to a true value or called without a value before rendering response headers, CGI::Tiny will act as
a NPH (Non-Parsed Header) <https://tools.ietf.org/html/rfc3875#section-5> script and render full HTTP
response headers. This may be required for some CGI servers, or enable unbuffered responses or HTTP
extensions not supported by the CGI server.
No effect after response headers have been rendered.
set_response_body_buffer
$cgi = $cgi->set_response_body_buffer(128*1024);
Sets the buffer size (number of bytes to read at once) for streaming a "file" or "handle" response body
with "render" or "render_chunk". Defaults to the value of the "CGI_TINY_RESPONSE_BODY_BUFFER" environment
variable or 131072 (128 KiB). A value of 0 will use the default value.
set_response_status
$cgi = $cgi->set_response_status(404);
$cgi = $cgi->set_response_status('500 Internal Server Error');
Sets the response HTTP status code. A full status string including a human-readable message will be used
as-is. A bare status code must be a known HTTP status code <https://www.iana.org/assignments/http-status-
codes/http-status-codes.xhtml> and will have the standard human-readable message appended.
No effect after response headers have been rendered.
The CGI protocol assumes a status of "200 OK" if no response status is set.
set_response_disposition
$cgi = $cgi->set_response_disposition('attachment');
$cgi = $cgi->set_response_disposition(attachment => $filename);
$cgi = $cgi->set_response_disposition('inline'); # default behavior
$cgi = $cgi->set_response_disposition(inline => $filename);
Sets the response "Content-Disposition" header to indicate how the client should present the response,
with an optional filename specified in Unicode characters. "attachment" suggests to download the content
as a file, and "inline" suggests to display the content inline (the default behavior). No effect after
response headers have been rendered.
set_response_type
$cgi = $cgi->set_response_type('application/xml');
Sets the response "Content-Type" header, to override autodetection in "render" or "render_chunk". "undef"
will remove the override. No effect after response headers have been rendered.
set_response_charset
$cgi = $cgi->set_response_charset('UTF-8');
Set charset to use when rendering "text", "html", or "xml" response content, defaults to "UTF-8".
add_response_header
$cgi = $cgi->add_response_header('Content-Language' => 'en');
Adds a custom response header. No effect after response headers have been rendered.
NOTE: Header names are case insensitive and CGI::Tiny does not attempt to deduplicate or munge headers
that have been added manually. Headers are printed in the response in the same order added, and adding
the same header multiple times will result in multiple instances of that response header.
add_response_cookie
$cgi = $cgi->add_response_cookie($name => $value,
Expires => 'Sun, 06 Nov 1994 08:49:37 GMT',
HttpOnly => 1,
'Max-Age' => 3600,
Path => '/foo',
SameSite => 'Strict',
Secure => 1,
);
Adds a "Set-Cookie" response header. No effect after response headers have been rendered.
Cookie values should consist only of simple ASCII text; see "Cookies" in CGI::Tiny::Cookbook for methods
of storing more complex strings and data structures.
Optional cookie attributes are specified in key-value pairs after the cookie name and value. Cookie
attribute names are case-insensitive.
Domain
Domain for which cookie is valid. Defaults to the host of the current document URL, not including
subdomains.
Expires
Expiration date string for cookie. Defaults to persisting for the current browser session.
"epoch_to_date" can be used to generate the appropriate date string format.
HttpOnly
If set to a true value, the cookie will be restricted from client-side scripts.
Max-Age
Max age of cookie before it expires, in seconds, as an alternative to specifying "Expires".
Path
URL path for which cookie is valid.
SameSite
"Strict" to restrict the cookie to requests from the same site, "Lax" to allow it additionally in
certain cross-site requests. This attribute is currently part of a draft specification so its
handling may change, but it is supported by most browsers.
Secure
If set to a true value, the cookie will be restricted to HTTPS requests.
reset_response_headers
$cgi = $cgi->reset_response_headers;
Remove any pending response headers set by "add_response_header" or "add_response_cookie". No effect
after response headers have been rendered.
response_status_code
my $code = $cgi->response_status_code;
Numerical response HTTP status code that will be sent when headers are rendered, as set by
"set_response_status" or an error occurring. Defaults to 200.
render
$cgi = $cgi->render; # default Content-Type:
$cgi = $cgi->render(text => $text); # text/plain;charset=$charset
$cgi = $cgi->render(html => $html); # text/html;charset=$charset
$cgi = $cgi->render(xml => $xml); # application/xml;charset=$charset
$cgi = $cgi->render(json => $ref); # application/json;charset=UTF-8
$cgi = $cgi->render(data => $bytes); # application/octet-stream
$cgi = $cgi->render(file => $filepath); # application/octet-stream
$cgi = $cgi->render(redirect => $url);
Renders response headers and then fixed-length response content of a type indicated by the first
parameter, if any. A "Content-Length" header will be set to the length of the encoded response content,
and further calls to "render" or "render_chunk" will throw an exception. Use "render_chunk" instead to
render without a "Content-Length" header.
The "Content-Type" response header will be set according to "set_response_type", or autodetected
depending on the data type of any non-empty response content passed.
The "Date" response header will be set to the current time as an HTTP date string if not set manually.
If the "request_method" is "HEAD", any provided response content will be ignored (other than redirect
URLs) and "Content-Length" will be set to 0.
"text", "html", or "xml" data is expected to be decoded Unicode characters, and will be encoded according
to "set_response_charset" (UTF-8 by default). Unicode::UTF8 will be used for efficient UTF-8 encoding if
available.
"json" data structures will be encoded to JSON and UTF-8.
"data" or "file" will render bytes from a string or local file path respectively. A "handle", or a "file"
whose size cannot be determined accurately from the filesystem, must be rendered using "render_chunk"
since its "Content-Length" cannot be determined beforehand.
"redirect" will set a "Location" header to redirect the client to another URL. The response status will
be set to 302 Found unless a different 300-level status has been set with "set_response_status". It will
set a "Content-Length" of 0, and it will not set a "Content-Type" response header.
render_chunk
$cgi = $cgi->render_chunk; # default Content-Type:
$cgi = $cgi->render_chunk(text => $text); # text/plain;charset=$charset
$cgi = $cgi->render_chunk(html => $html); # text/html;charset=$charset
$cgi = $cgi->render_chunk(xml => $xml); # application/xml;charset=$charset
$cgi = $cgi->render_chunk(json => $ref); # application/json;charset=UTF-8
$cgi = $cgi->render_chunk(data => $bytes); # application/octet-stream
$cgi = $cgi->render_chunk(file => $filepath); # application/octet-stream
$cgi = $cgi->render_chunk(handle => $filehandle); # application/octet-stream
Renders response headers the first time it is called, and then chunked response content of a type
indicated by the first parameter, if any. No "Content-Length" header will be set, and "render_chunk" may
be called additional times with more response content.
"render_chunk" does not impose a chunked response, it simply does not generate a "Content-Length" header.
For content where the total encoded content length is known in advance but the content can't be passed to
a single "render" call, a "Content-Length" header can be set manually with "add_response_header", and
then "render_chunk" may be used to render each part.
The "Content-Type" response header will be set according to "set_response_type", or autodetected
depending on the data type passed in the first call to "render_chunk", or to "application/octet-stream"
if there is no more appropriate value. It will be set even if no content is passed to the first
"render_chunk" call, in case content is rendered in subsequent calls.
The "Date" response header will be set to the current time as an HTTP date string if not set manually.
If the "request_method" is "HEAD", any provided response content will be ignored.
"text", "html", or "xml" data is expected to be decoded Unicode characters, and will be encoded according
to "set_response_charset" (UTF-8 by default). Unicode::UTF8 will be used for efficient UTF-8 encoding if
available.
"json" data structures will be encoded to JSON and UTF-8.
"data", "file", or "handle" will render bytes from a string, local file path, or open filehandle
respectively. A "handle" will have "binmode" applied to remove any translation layers, and its contents
will be streamed until EOF.
"redirect" responses must be rendered with "render".