CGI-Tiny
view release on metacpan or search on metacpan
lib/CGI/Tiny.pod view on Meta::CPAN
L</"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.
B<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 L<Syntax::Keyword::Try> or L<Feature::Compat::Try>
(which will use the new C<try> feature if available).
=head3 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 C<CGI_TINY_REQUEST_BODY_BUFFER> environment
variable or 262144 (256 KiB). A value of 0 will use the default value.
=head3 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
C<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 L</"body"> or L</"upload"> will set the response status to
C<413 Payload Too Large> and throw an exception if the content length is over
the limit. Files uploaded through a C<multipartE<sol>form-data> request body
also count toward this limit, though they are streamed to temporary files when
parsed.
=head3 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
C<multipartE<sol>form-data> request body with
L<CGI::Tiny::Multipart/"parse_multipart_form_data">. No effect after the form
data has been parsed such as by calling L</"body_params"> or L</"uploads"> for
the first time.
B<NOTE:> Options like C<parse_as_files> and C<on_file_buffer> can alter the
C<content> and C<file> keys of the form field structure returned by
L</"body_parts">. Thus L</"uploads"> may not contain C<file> and may instead
contain C<content>, and L</"body_params"> text field values may be read from
C<file>, which will be expected to be a seekable filehandle if present.
=head3 set_multipart_form_charset
$cgi = $cgi->set_multipart_form_charset('UTF-8');
Sets the default charset for decoding C<multipartE<sol>form-data> forms,
defaults to C<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 C<ISO-8859-1>.
=head3 set_input_handle
$cgi = $cgi->set_input_handle($fh);
Sets the input handle to read the request body from. If not set, reads from
C<STDIN>. The handle will have C<binmode> applied before reading to remove any
translation layers.
=head3 set_output_handle
$cgi = $cgi->set_output_handle($fh);
Sets the output handle to print the response to. If not set, prints to
C<STDOUT>. The handle will have C<binmode> applied before printing to remove
any translation layers.
=head2 Request Environment
CGI::Tiny provides direct access to CGI
L<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.
=head3 auth_type
# AUTH_TYPE="Basic"
my $auth_type = $cgi->auth_type;
The authentication scheme used in the C<Authorization> HTTP request header if
any.
=head3 content_length
# CONTENT_LENGTH="42"
my $content_length = $cgi->content_length;
The size in bytes of the request body content if any.
=head3 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.
=head3 gateway_interface
# GATEWAY_INTERFACE="CGI/1.1"
my $gateway_inteface = $cgi->gateway_interface;
The CGI version used for communication with the CGI server.
=head3 path_info
=head3 path
lib/CGI/Tiny.pod view on Meta::CPAN
=head3 server_software
# SERVER_SOFTWARE="Apache\/2.4.37 (centos)"
my $server_software = $cgi->server_software;
The name and version of the CGI server.
=head2 Request Parsing
=head3 headers
my $hashref = $cgi->headers;
Hash reference of available request header names and values. Header names are
represented in lowercase.
=head3 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.
=head3 cookies
my $pairs = $cgi->cookies;
Retrieve request cookies as an ordered array reference of name/value pairs,
represented as two-element array references.
=head3 cookie_names
my $arrayref = $cgi->cookie_names;
Retrieve request cookie names as an ordered array reference, without
duplication.
=head3 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 L</"cookie_array"> to get
multiple values of a cookie name.
=head3 cookie_array
my $arrayref = $cgi->cookie_array('foo');
Retrieve values of a request cookie name as an ordered array reference.
=head3 params
my $pairs = $cgi->params;
Retrieve URL query string parameters and C<application/x-www-form-urlencoded>
or C<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
L</"query_params"> or L</"body_params"> to retrieve query or body parameters
separately.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 param_names
my $arrayref = $cgi->param_names;
Retrieve URL query string parameter names and
C<application/x-www-form-urlencoded> or C<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
L</"query_param_names"> or L</"body_param_names"> to retrieve query or body
parameter names separately.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 param
my $value = $cgi->param('foo');
Retrieve value of a named URL query string parameter or
C<application/x-www-form-urlencoded> or C<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
L</"param_array"> to get multiple values of a parameter, or L</"query_param">
or L</"body_param"> to retrieve the last query or body parameter value
specifically.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 param_array
my $arrayref = $cgi->param_array('foo');
Retrieve values of a named URL query string parameter or
C<application/x-www-form-urlencoded> or C<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 L</"query_param_array"> or L</"body_param_array"> to retrieve query
or body parameter values separately.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 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.
=head3 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.
=head3 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
L</"query_param_array"> to get multiple values of a parameter.
=head3 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.
=head3 body
my $bytes = $cgi->body;
Retrieve the request body as bytes.
B<NOTE:> This will read the whole request body into memory, so make sure the
L</"set_request_body_limit"> can fit well within the available memory.
Not available after calling L</"body_parts">, L</"body_params">, or
L</"uploads"> (or related accessors) on a C<multipartE<sol>form-data> request,
since this type of request body is not retained in memory after parsing.
=head3 body_json
my $data = $cgi->body_json;
Decode an C<application/json> request body from UTF-8-encoded JSON.
B<NOTE:> This will read the whole request body into memory, so make sure the
L</"set_request_body_limit"> can fit well within the available memory.
=head3 body_params
my $pairs = $cgi->body_params;
Retrieve C<applicationE<sol>x-www-form-urlencoded> or
C<multipartE<sol>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.
B<NOTE:> This will read the text form fields into memory, so make sure the
L</"set_request_body_limit"> can fit well within the available memory.
C<multipartE<sol>form-data> file uploads will be streamed to temporary files
accessible via L</"uploads"> and related methods.
=head3 body_param_names
my $arrayref = $cgi->body_param_names;
Retrieve C<applicationE<sol>x-www-form-urlencoded> or
C<multipartE<sol>form-data> body parameter names, decoded to Unicode
characters, as an ordered array reference, without duplication.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 body_param
my $value = $cgi->body_param('foo');
Retrieve value of a named C<applicationE<sol>x-www-form-urlencoded> or
C<multipartE<sol>form-data> body parameter, decoded to Unicode characters.
If the parameter name was passed multiple times, returns the last value. Use
L</"body_param_array"> to get multiple values of a parameter.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 body_param_array
my $arrayref = $cgi->body_param_array('foo');
Retrieve values of a named C<applicationE<sol>x-www-form-urlencoded> or
C<multipartE<sol>form-data> body parameter, decoded to Unicode characters, as
an ordered array reference.
B<NOTE:> This will read the text form fields into memory as in
L</"body_params">.
=head3 body_parts
my $parts = $cgi->body_parts;
Retrieve C<multipartE<sol>form-data> request body parts as an ordered array
reference using L<CGI::Tiny::Multipart/"parse_multipart_form_data">. Most
applications should retrieve multipart form data through L</"body_params"> and
L</"uploads"> (or related accessors) instead.
B<NOTE:> This will read the text form fields into memory, so make sure the
L</"set_request_body_limit"> can fit well within the available memory. File
uploads will be streamed to temporary files.
=head3 uploads
my $pairs = $cgi->uploads;
Retrieve C<multipartE<sol>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.
B<NOTE:> This will read the text form fields into memory, so make sure the
L</"set_request_body_limit"> can fit well within the available memory.
File uploads are represented as a hash reference containing the following keys:
=over
=item filename
Original filename supplied to file input. An empty filename may indicate that
no file was submitted.
=item content_type
C<Content-Type> of uploaded file, undef if unspecified.
=item size
File size in bytes.
=item file
L<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 C<seek> pointer at the start of the file for reading.
=back
=head3 upload_names
my $arrayref = $cgi->upload_names;
Retrieve C<multipartE<sol>form-data> file upload names, decoded to Unicode
characters, as an ordered array reference, without duplication.
B<NOTE:> This will read the text form fields into memory as in L</"uploads">.
=head3 upload
my $upload = $cgi->upload('foo');
Retrieve a named C<multipartE<sol>form-data> file upload. If the upload name
was passed multiple times, returns the last value. Use L</"upload_array">
to get multiple uploads with the same name.
See L</"uploads"> for details on the representation of the upload.
B<NOTE:> This will read the text form fields into memory as in L</"uploads">.
=head3 upload_array
my $arrayref = $cgi->upload_array('foo');
Retrieve all C<multipartE<sol>form-data> file uploads of the specified name as
an ordered array reference.
See L</"uploads"> for details on the representation of the uploads.
B<NOTE:> This will read the text form fields into memory as in L</"uploads">.
=head2 Response
=head3 set_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
L<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.
=head3 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 C<file>
or C<handle> response body with L</"render"> or L</"render_chunk">. Defaults to
the value of the C<CGI_TINY_RESPONSE_BODY_BUFFER> environment variable or
131072 (128 KiB). A value of 0 will use the default value.
=head3 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
L<HTTP status code|https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml>
lib/CGI/Tiny.pod view on Meta::CPAN
=item Path
URL path for which cookie is valid.
=item SameSite
C<Strict> to restrict the cookie to requests from the same site, C<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.
=item Secure
If set to a true value, the cookie will be restricted to HTTPS requests.
=back
=head3 reset_response_headers
$cgi = $cgi->reset_response_headers;
Remove any pending response headers set by L</"add_response_header"> or
L</"add_response_cookie">. No effect after response headers have been rendered.
=head3 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 L</"set_response_status"> or an error occurring. Defaults
to C<200>.
=head3 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 C<Content-Length> header will be
set to the length of the encoded response content, and further calls to
C<render> or L</"render_chunk"> will throw an exception. Use L</"render_chunk">
instead to render without a C<Content-Length> header.
The C<Content-Type> response header will be set according to
L</"set_response_type">, or autodetected depending on the data type of any
non-empty response content passed.
The C<Date> response header will be set to the current time as an HTTP date
string if not set manually.
If the L</"request_method"> is C<HEAD>, any provided response content will be
ignored (other than redirect URLs) and C<Content-Length> will be set to 0.
C<text>, C<html>, or C<xml> data is expected to be decoded Unicode characters,
and will be encoded according to L</"set_response_charset"> (UTF-8 by default).
L<Unicode::UTF8> will be used for efficient UTF-8 encoding if available.
C<json> data structures will be encoded to JSON and UTF-8.
C<data> or C<file> will render bytes from a string or local file path
respectively. A C<handle>, or a C<file> whose size cannot be determined
accurately from the filesystem, must be rendered using L</"render_chunk"> since
its C<Content-Length> cannot be determined beforehand.
C<redirect> will set a C<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 L</"set_response_status">. It will set a
C<Content-Length> of 0, and it will not set a C<Content-Type> response header.
=head3 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
C<Content-Length> header will be set, and C<render_chunk> may be called
additional times with more response content.
C<render_chunk> does not impose a chunked response, it simply does not generate
a C<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 L</"render">
call, a C<Content-Length> header can be set manually with
L</"add_response_header">, and then C<render_chunk> may be used to render each
part.
The C<Content-Type> response header will be set according to
L</"set_response_type">, or autodetected depending on the data type passed in
the first call to C<render_chunk>, or to C<application/octet-stream> if there
is no more appropriate value. It will be set even if no content is passed to
the first C<render_chunk> call, in case content is rendered in subsequent
calls.
The C<Date> response header will be set to the current time as an HTTP date
string if not set manually.
If the L</"request_method"> is C<HEAD>, any provided response content will be
ignored.
C<text>, C<html>, or C<xml> data is expected to be decoded Unicode characters,
and will be encoded according to L</"set_response_charset"> (UTF-8 by default).
L<Unicode::UTF8> will be used for efficient UTF-8 encoding if available.
C<json> data structures will be encoded to JSON and UTF-8.
C<data>, C<file>, or C<handle> will render bytes from a string, local file
path, or open filehandle respectively. A C<handle> will have C<binmode> applied
to remove any translation layers, and its contents will be streamed until EOF.
C<redirect> responses must be rendered with L</"render">.
=head1 FUNCTIONS
The following convenience functions are provided but not exported.
=head2 epoch_to_date
my $date = CGI::Tiny::epoch_to_date $epoch;
Convert a Unix epoch timestamp, such as returned by C<time>, to a RFC 1123 HTTP
date string suitable for use in HTTP headers such as C<Date> and C<Expires>.
=head2 date_to_epoch
my $epoch = CGI::Tiny::date_to_epoch $date;
Parse a RFC 1123 HTTP date string to a Unix epoch timestamp. For compatibility
as required by L<RFC 7231|https://tools.ietf.org/html/rfc7231#section-7.1.1.1>,
legacy RFC 850 and ANSI C asctime date formats are also recognized. Returns
C<undef> if the string does not parse as any of these formats.
# RFC 1123
my $epoch = CGI::Tiny::date_to_epoch 'Sun, 06 Nov 1994 08:49:37 GMT';
# RFC 850
my $epoch = CGI::Tiny::date_to_epoch 'Sunday, 06-Nov-94 08:49:37 GMT';
# asctime
my $epoch = CGI::Tiny::date_to_epoch 'Sun Nov 6 08:49:37 1994';
=head2 escape_html
my $escaped = CGI::Tiny::escape_html $text;
Escapes characters that are unsafe for embedding in HTML text. The characters
C<&E<lt>E<gt>"'> will each be replaced with the corresponding HTML character
reference (HTML entity).
This functionality is built into most HTML template engines; see
L<CGI::Tiny::Cookbook/"Templating">. For more general HTML entity escaping and
unescaping use L<HTML::Entities>.
=head1 ENVIRONMENT
CGI::Tiny recognizes the following environment variables, in addition to the
standard CGI environment variables.
=over
=item CGI_TINY_REQUEST_BODY_BUFFER
( run in 0.700 second using v1.01-cache-2.11-cpan-39bf76dae61 )