CGI::Tiny(3pm)

πŸ“¦
version 1.003 Β· 2 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

πŸ’– CGI::Tiny(3pm) β€” User Contributed Perl Documentation πŸ’–

CGI::Tiny(3pm) is the manual name, bestie, and this is the User Contributed Perl Documentation page for CGI::Tiny. It's giving "we're about to make CGI scripts cute and competent" energy. πŸ’…


✨ NAME ✨

CGI::Tiny β€” Common Gateway Interface, with no frills. No frills, just vibes. πŸŽ€


🌸 SYNOPSIS 🌸

#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;

cgi {
  my $cgi = $_;
  $cgi->set_error_handler(sub {
    my ($cgi, $error, $rendered) = @_;
    warn $error;
    unless ($rendered) {
      if ($cgi->response_status_code == 413) {
        $cgi->render(json => {error => 'Request body limit exceeded'});
      } elsif ($cgi->response_status_code == 400) {
        $cgi->render(json => {error => 'Bad request'});
      } else {
        $cgi->render(json => {error => 'Internal server error'});
      }
    }
  });

  my $method = $cgi->method;
  my $fribble;
  if ($method eq 'GET' or $method eq 'HEAD') {
    $fribble = $cgi->query_param('fribble');
  } elsif ($method eq 'POST') {
    $fribble = $cgi->body_param('fribble');
  } else {
    $cgi->set_response_status(405)->render;
    exit;
  }
  die "Invalid fribble parameter" unless length $fribble;

  if ($cgi->param('download')) {
    $cgi->set_response_disposition(attachment => 'fribble.json');
  }
  $cgi->render(json => {fribble => $fribble});
};

πŸ¦‹ DESCRIPTION πŸ¦‹

CGI::Tiny provides a modern interface to write CGI scripts (https://en.wikipedia.org/wiki/Common_Gateway_Interface) to dynamically respond to HTTP requests as defined in RFC 3875 (https://tools.ietf.org/html/rfc3875). It is intended to be:

  • Minimal β€” CGI::Tiny contains a small amount of code and (on modern Perls) no non-core requirements. No framework needed.
  • Simple β€” CGI::Tiny is straightforward to use, avoids anything magical or surprising, and provides easy access to the most commonly needed features.
  • Robust β€” CGI::Tiny's interface is designed to help the developer follow best practices and avoid common pitfalls and vulnerabilities by default.
  • Lazy β€” CGI::Tiny only loads code or processes information once it is needed, so simple requests can be handled without unnecessary overhead.
  • Restrained β€” CGI::Tiny is designed for the CGI protocol which executes the program again for every request. It is not suitable for persistent protocols like FastCGI or PSGI.
  • Flexible β€” CGI::Tiny can be used with other modules to handle tasks like routing and templating, and doesn't impose unnecessary constraints to reading input or rendering output.

Most applications are better written in a PSGI-compatible framework (e.g. Dancer2 or Mojolicious) and deployed in a persistent application server so that the application does not have to start up again every time it receives a request. CGI::Tiny, and the CGI protocol in general, is only suited for restricted deployment environments that can only run CGI scripts, or applications that don't need to scale.

See "COMPARISON TO CGI.PM".


🫢 USAGE 🫢

CGI::Tiny's interface is the cgi block. Periodt.

use CGI::Tiny;
cgi {
  my $cgi = $_;
  # set up error handling on $cgi
  # inspect request data via $cgi
  # set response headers if needed via $cgi
  # render response with $cgi->render or $cgi->render_chunk
};

The block is immediately run with $_ set to a CGI::Tiny object, which "METHODS" can be called on to read request information and render a response.

If an exception is thrown within the block, or the block does not render a response, it will run the handler set by "set_error_handler" if any, or by default emit the error as a warning and (if nothing has been rendered yet) render a 500 Internal Server Error.

The default server error will also be rendered if the process ends abnormally between importing from CGI::Tiny and the start of the "cgi" block. To load CGI::Tiny without triggering this cleanup mechanism or making the "cgi" block available (such as to use convenience "FUNCTIONS" in non-CGI code), load the module with use CGI::Tiny (); or require CGI::Tiny;.

NOTE: The "cgi" block's current implementation as a regular exported subroutine is an implementation detail, and future implementations reserve the right to provide it as an XSUB or keyword for performance reasons. Don't call it as CGI::Tiny::cgi, don't rely on @_ being set, and don't use return to exit the block; use exit to end a CGI script early after rendering a response.

See CGI::Tiny::Cookbook for advanced usage examples.


πŸ›‘οΈ DATA SAFETY πŸ›‘οΈ

CGI::Tiny does not provide any special affordances for taint mode as it is overeager, imprecise, and can significantly impact performance. Web developers should instead proactively take care not to use any request data (including request headers, form fields, or other request content) directly in an unsafe manner, as it can make the program vulnerable to injections that cause undesired or dangerous behavior. The most common risks to watch out for include:

  • System commands β€” Do not interpolate arbitrary data into a shell command, such as with system or backticks. Data can be safely passed as command arguments using methods that bypass the shell, such as the list form of system, or modules like IPC::System::Simple, IPC::ReadpipeX, and IPC::Run3. If shell features are needed, data can be escaped for bourne-style shells with String::ShellQuote.
  • Database queries β€” Do not interpolate arbitrary data into database queries. Data can be safely passed to database queries using placeholders (https://metacpan.org/pod/DBI#Placeholders-and-Bind-Values).
  • Regex β€” Do not interpolate arbitrary data into regular expressions, such as the m// or s/// operators, or the first argument to split. Data can be safely included in a regex to match it as an exact string by escaping it with the quotemeta function or equivalent \Q escape sequence.
  • HTML β€” Do not interpolate arbitrary data into HTML. Data can be safely included in HTML by escaping it with escape_html, or passing it to an HTML template engine with an auto-escape feature; see "Templating" in CGI::Tiny::Cookbook.

πŸ’… METHODS πŸ’…

The following methods can be called on the CGI::Tiny object provided to the "cgi" block.

Setup

set_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.

🌸 Request Environment 🌸

okay bestie so here's the whole vibe: CGI::Tiny gives you direct access to the CGI request meta-variables (<https://tools.ietf.org/html/rfc3875#section-4.1> β€” yes that link, keep it) through methods that map straight onto the equivalent uppercase names, plus a few short aliases for the ones you'll be typing a million times a day. πŸŽ€

And listen: since CGI genuinely does not distinguish between missing and empty values, missing values get normalized to an empty string. So no surprise undef, no sad warnings, just vibes. ✨

auth_type

# AUTH_TYPE="Basic"
my $auth_type = $cgi->auth_type;

The authentication scheme used in the Authorization HTTP request header, if any. Lowkey the "who are you and how did you prove it" field. πŸ•΅οΈ

content_length

# CONTENT_LENGTH="42"
my $content_length = $cgi->content_length;

The size, in bytes, of the request body content, if any. It's giving "how much is about to hit me". πŸ“

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. The main character label on your payload. 🏷️

gateway_interface

# GATEWAY_INTERFACE="CGI/1.1"
my $gateway_inteface = $cgi->gateway_interface;

The CGI version used for communication with the CGI server. (And yes, the variable in that example is literally spelled $gateway_inteface β€” iconic typo, we keep it, no cap.) πŸ’€

path_info, path

# 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 is just the short lil alias because why type eight more letters. πŸ¦‹

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. Keyword: if. Not every server does. πŸ™ˆ

query_string, query

# QUERY_STRING="foo=bar"
my $query = $cgi->query_string;
my $query = $cgi->query;

The query string component of the request URL. The raw one. Pre-decoding. The unedited footage. 🎬

remote_addr

# REMOTE_ADDR="8.8.8.8"
my $remote_addr = $cgi->remote_addr;

The IPv4 or IPv6 address of the requesting client. Their actual coordinates. πŸ“

remote_host

# REMOTE_HOST="example.com"
my $remote_host = $cgi->remote_host;

The domain name of the requesting client if available, or REMOTE_ADDR. So basically "name if we got one, IP if we didn't". πŸ€·β€β™€οΈ

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. Ancient lore, but it's here. 🏺

remote_user

# REMOTE_USER="someuser"
my $remote_user = $cgi->remote_user;

The user identity provided as part of an AUTH_TYPE authenticated request. The "we know it's you" field. πŸ”

request_method, method

# REQUEST_METHOD="GET"
my $method = $cgi->request_method;
my $method = $cgi->method;

The HTTP request method verb. GET, POST, whatever energy the client is bringing. ⚑

script_name

# SCRIPT_NAME="/cgi-bin/script.cgi"
my $script_name = $cgi->script_name;

The host-relative URL path to the CGI script. Where you live. 🏑

server_name

# SERVER_NAME="example.com"
my $server_name = $cgi->server_name;

The hostname of the server as the target of the request, like 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. Old money or new money, it'll tell you. πŸ’…

server_software

# SERVER_SOFTWARE="Apache\/2.4.37 (centos)"
my $server_software = $cgi->server_software;

The name and version of the CGI server. Full government name. πŸͺͺ


πŸ“ Request Parsing πŸ“

Now we get to the good part β€” actually pulling stuff out of the request. Same energy as unboxing but it's form data. 😭

headers

my $hashref = $cgi->headers;

Hash reference of the available request header names and values. Header names come out in lowercase, so don't come at it with Content-Type and expect a match. πŸ™…β€β™€οΈ

my $value = $cgi->header('Accept-Language');

Grab the value of a request header by name (case insensitive). And heads up: CGI request headers can only contain a single value, which may be combined from multiple values. So you get one string, not a list. Periodt. πŸ’…

cookies

my $pairs = $cgi->cookies;

Retrieve request cookies as an ordered array reference of name/value pairs, each pair represented as a two-element array reference. Order is preserved, nothing merged. πŸͺ

my $arrayref = $cgi->cookie_names;

Retrieve request cookie names as an ordered array reference, without duplication. The guest list, no repeats. πŸ“‹

my $value = $cgi->cookie('foo');

Retrieve the value of a request cookie by name. If multiple cookies came through with the same name, you get the last value. Need all of them? Use cookie_array. 🫢

my $arrayref = $cgi->cookie_array('foo');

Retrieve values of a request cookie name as an ordered array reference. All of them. The whole squad. πŸŽ€

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, each pair a two-element array reference. Names and values are decoded to Unicode characters.

Query parameters come back first, body parameters after. Want them separately? Use query_params or body_params.

NOTE: This will read the text form fields into memory as in body_params. So mind your memory, bestie. 🧠

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 come first, body parameter names after. For just one side of that, use query_param_names or body_param_names.

NOTE: This will read the text form fields into memory as in body_params. Same warning, same energy. 🧠

param

my $value = $cgi->param('foo');

Retrieve the 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, you get the last body parameter value if there is one, otherwise the last query parameter value. Want them all? param_array. Want specifically the last query or body one? query_param or body_param.

NOTE: This will read the text form fields into memory as in body_params. Yeah. Again. 🧠

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 come first, body parameter values follow. Use query_param_array or body_param_array to get one side or the other on its own.

NOTE: This will read the text form fields into memory as in body_params. You know the drill. 🧠

query_params

my $pairs = $cgi->query_params;

Retrieve URL query string parameters as an ordered array reference of name/value pairs, each pair a two-element array reference. Names and values are decoded to Unicode characters. Query-only, no body shenanigans. ✨

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 the value of a named URL query string parameter, decoded to Unicode characters.

If the parameter name was passed multiple times, you get the last value. Use query_param_array for multiple values. πŸ’–

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. Raw. Untouched.

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. Do not play with this one. 😭

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. Once it's gone, it's gone. πŸ’€

body_json

my $data = $cgi->body_json;

Decode an application/json request body from UTF-8-encoded JSON. Slay.

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. Same rule, same stakes. 🧠

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, each pair a two-element array reference. 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 the 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, you get the last value. Use body_param_array for multiple values.

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 β€” this is the deep-lore version. 🏺

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, each pair a two-element array reference. 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 β€” the original filename that got handed to the file input. Heads up: an empty filename might mean no file was actually submitted, so don't just assume it's there bestie.
  • content_type β€” the Content-Type of the uploaded file. If nobody specified one, it's undef. πŸ™ˆ
  • size β€” the file size, in bytes. Periodt.
  • file β€” a File::Temp object holding the file contents in a temp file. By default this gets cleaned up the moment the CGI script ends, so no mystery leftovers. The filehandle comes open with the seek pointer chilling at the start of the file, ready for reading. πŸ’…

upload_names

my $arrayref = $cgi->upload_names;

Grabs all the multipart/form-data file upload names, decoded into Unicode characters, and hands them to you as an ordered array reference with zero duplicates. Clean list, no repeats, we love to see it. ✨

NOTE: this will read the text form fields into memory, same as in uploads.

upload

my $upload = $cgi->upload('foo');

Retrieves one named multipart/form-data file upload. If that upload name got passed in multiple times, you get the last value back. If you want all of them with the same name, use upload_array instead β€” she's the one for that. πŸ‘‘

Check out uploads for the deets on how the upload is represented.

NOTE: this will read the text form fields into memory, same as in uploads.

upload_array

my $arrayref = $cgi->upload_array('foo');

Retrieves every multipart/form-data file upload with the name you asked for, as an ordered array reference. All of them, in order, no crumbs left behind. πŸ“

Check out uploads for the deets on how those uploads are represented.

NOTE: this will read the text form fields into memory, same as in uploads.

🌈 Response 🌈

set_nph

$cgi = $cgi->set_nph;
$cgi = $cgi->set_nph(1);

If you set this to a true value, or just call it with no value at all, before the response headers get rendered, then CGI::Tiny will act like an NPH (Non-Parsed Header) script β€” see <https://tools.ietf.org/html/rfc3875#section-5> β€” and render the full HTTP response headers. Some CGI servers literally need this. It can also unlock unbuffered responses, or HTTP extensions your CGI server just doesn't support otherwise. Main character energy for your headers. πŸ‘‘

No effect once the response headers have already been rendered. Too late, babe.


set_response_body_buffer

$cgi = $cgi->set_response_body_buffer(128*1024);

Sets the buffer size β€” that's the number of bytes read at once β€” when you're streaming a file or handle response body through render or render_chunk. It defaults to whatever the CGI_TINY_RESPONSE_BODY_BUFFER environment variable says, or 131072 (128 KiB) if that's not a thing. Passing 0 means "just use the default". πŸ’œ


set_response_status

$cgi = $cgi->set_response_status(404);
$cgi = $cgi->set_response_status('500 Internal Server Error');

Sets the response HTTP status code. If you hand it a full status string with a human-readable message, it uses that exactly as-is, no notes. If you hand it a bare status code, it has to be a known HTTP status code β€” see <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml> β€” and the standard human-readable message gets appended for you. πŸŽ€

No effect after the response headers have been rendered. Sorry bestie, the window's closed.

The CGI protocol just assumes a status of 200 OK if you never set one.


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, which is the thing that tells the client how to present your response. You can optionally pass a filename too, given in Unicode characters. attachment is the "please download this as a file" vibe, and inline is the "just show it right here" vibe β€” and inline is the default behavior. No effect once the response headers have been rendered. πŸ¦‹


set_response_type

$cgi = $cgi->set_response_type('application/xml');

Sets the response Content-Type header, which lets you override the autodetection that render or render_chunk would otherwise do. Passing undef removes the override. No effect after the response headers have been rendered. ✨


set_response_charset

$cgi = $cgi->set_response_charset('UTF-8');

Sets the charset used 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 once the response headers have been rendered.

NOTE: header names are case insensitive, and CGI::Tiny does not try to deduplicate or munge headers you've added manually. Headers get printed in the response in the exact order you added them, and adding the same header multiple times means you get multiple instances of that response header. It's giving exactly what you asked for, no corrections. πŸ’€

$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 the response headers have been rendered.

Cookie values should really only be simple ASCII text. If you wanna store fancier strings or whole data structures, go look at "Cookies" in CGI::Tiny::Cookbook β€” that's where those methods live. πŸ“

Optional cookie attributes go in key-value pairs after the cookie name and value. Cookie attribute names are case-insensitive, so don't stress about the casing.

  • Domain β€” the domain this cookie is valid for. Defaults to the host of the current document URL, and it does not include subdomains.
  • Expires β€” the expiration date string for the cookie. Defaults to lasting just for the current browser session. You can use epoch_to_date to generate the right date string format. πŸŽ€
  • HttpOnly β€” if set to a true value, the cookie gets restricted from client-side scripts. Sneaky scripts, not today.
  • Max-Age β€” the max age of the cookie before it expires, in seconds. This is an alternative to specifying Expires.
  • Path β€” the URL path this cookie is valid for.
  • SameSite β€” Strict restricts the cookie to requests from the same site, and Lax allows it additionally in certain cross-site requests. Heads up: this attribute is currently part of a draft specification, so its handling may change β€” but most browsers support it, so we move.
  • Secure β€” if set to a true value, the cookie gets restricted to HTTPS requests only. πŸ”’

reset_response_headers

$cgi = $cgi->reset_response_headers;

Removes any pending response headers set by add_response_header or add_response_cookie. No effect after the response headers have been rendered. Fresh start, clean slate. 🧚


response_status_code

my $code = $cgi->response_status_code;

The numerical response HTTP status code that will be sent when the headers get rendered β€” either as set by set_response_status, or from an error that occurred. 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 the response headers, and then fixed-length response content of whatever type the first parameter says β€” if you passed one at all. A Content-Length header gets set to the length of the encoded response content, and any further calls to render or render_chunk will throw an exception. So like, one and done. If you need to render without a Content-Length header, use render_chunk instead. πŸ’…

The Content-Type response header gets set according to set_response_type, or autodetected based on the data type of any non-empty response content you passed. ✨

The Date response header gets set to the current time as an HTTP date string, unless you set it manually yourself.

If the request_method is HEAD, any response content you provide gets ignored β€” other than redirect URLs β€” and Content-Length gets set to 0. Nothing to see here, literally.

text, html, or xml data is expected to be decoded Unicode characters, and gets encoded according to set_response_charset (UTF-8 by default). If Unicode::UTF8 is available, it'll be used for efficient UTF-8 encoding. Slay. πŸ”₯

json data structures get encoded to JSON and UTF-8.

data or file render bytes from a string or a local file path respectively. A handle, or a file whose size can't be determined accurately from the filesystem, must be rendered using render_chunk, because its Content-Length can't be figured out ahead of time. No guessing games.

redirect sets a Location header to redirect the client to another URL. The response status gets set to 302 Found unless you already set a different 300-level status with set_response_status. It sets a Content-Length of 0, and it does not set a Content-Type response header. Just a clean little bounce. πŸ¦‹


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 the response headers the first time you call it, and then chunked response content of whatever type the first parameter says β€” if any. No Content-Length header gets set, and you can call render_chunk again and again with more response content. Keep the party going. πŸŽ‰

Important: render_chunk does not force a chunked response. It just doesn't generate a Content-Length header. If you know the total encoded content length in advance but your content can't fit into a single render call, you can set a Content-Length header manually with add_response_header, then use render_chunk to render each part. iykyk. πŸ’œ

The Content-Type response header gets set according to set_response_type, or autodetected based on the data type you passed in the first call to render_chunk, or falls back to application/octet-stream if there's nothing more appropriate. It gets set even if you pass no content to that first render_chunk call β€” just in case content shows up in later calls. Prepared. πŸ‘‘

The Date response header gets set to the current time as an HTTP date string if you haven't set it manually.

If the request_method is HEAD, any provided response content gets ignored.

text, html, or xml data is expected to be decoded Unicode characters, and gets encoded according to set_response_charset (UTF-8 by default). If Unicode::UTF8 is available, it'll be used for efficient UTF-8 encoding. ✨

  • json β€” hand me a data structure and I'll encode it to JSON and UTF-8 for you. two jobs, one vibe πŸ’…
  • data, file, or handle β€” these render bytes, bestie. data = a plain string, file = a local file path, handle = an open filehandle. And a handle gets binmode applied to strip off any translation layers, then its contents get streamed all the way until EOF. no cap πŸ¦‹
  • redirect responses? those must be rendered with render. periodt.

✨ FUNCTIONS ✨

These little convenience cuties are provided for you, but heads up β€” they are not exported. so you have to call them fully qualified, iykyk πŸŽ€

πŸ•°οΈ epoch_to_date

my $date = CGI::Tiny::epoch_to_date $epoch;

Takes a Unix epoch timestamp β€” like the one time hands you β€” and turns it into a RFC 1123 HTTP date string, the kind that belongs in HTTP headers like Date and Expires. iconic behavior honestly ✨

πŸ“… date_to_epoch

my $epoch = CGI::Tiny::date_to_epoch $date;

The reverse glow-up: parses an RFC 1123 HTTP date string back into a Unix epoch timestamp. And because RFC 7231 <https://tools.ietf.org/html/rfc7231#section-7.1.1.1> requires this for compatibility, legacy RFC 850 and ANSI C asctime date formats are recognized too. If the string doesn't parse as any of these formats, you get back undef. 😭

# 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';

🌸 escape_html

my $escaped = CGI::Tiny::escape_html $text;

Escapes characters that are unsafe to embed in HTML text. Each of the characters &<>"' gets swapped for its corresponding HTML character reference (HTML entity). keeping you safe from the chaos, bestie 🫢

This functionality is literally built into most HTML template engines already; peep "Templating" in CGI::Tiny::Cookbook. And if you want more general HTML entity escaping and unescaping, go use HTML::Entities.


🌈 ENVIRONMENT 🌈

CGI::Tiny recognizes the following environment variables β€” on top of all the standard CGI environment variables you already know and love. πŸ’–

  • CGI_TINY_REQUEST_BODY_BUFFER β€” the default value for set_request_body_buffer.
  • CGI_TINY_REQUEST_BODY_LIMIT β€” the default value for set_request_body_limit.
  • CGI_TINY_RESPONSE_BODY_BUFFER β€” the default value for set_response_body_buffer.

πŸ› οΈ DEBUGGING COMMANDS πŸ› οΈ

Okay so this part is so useful. CGI::Tiny scripts can be run straight from the commandline for debugging purposes. You can pass a command as the first argument to help set up the CGI environment for you. πŸ’…

⚠️ These commands are considered a development interface and come with no stability guarantee. so don't go building your whole production life on them, bestie.
$ ./script.cgi get '/?foo=bar'
$ ./script.cgi head
$ ./script.cgi post '/form' -C 'one=value' -C 'two=value' --content='foo=bar+baz'
    -H 'Content-Type: application/x-www-form-urlencoded'
$ ./script.cgi put -H "Content-Length: $(stat --printf='%s' foo.dat)"
    -H "Content-Type: $(file -bi foo.dat)" <foo.dat
$ ./script.cgi delete -v '/item/42'

The get, head, post, put, and delete commands will emulate a request of the specified request_method. And if you follow it with a URL parameter, that gets passed as the path_info and query_string (when present). 🌟

Request content can come in through STDIN, but the Content-Length request header must be set to the size of the input, as required by the CGI spec. don't skip that part, fr fr.

The response prints to STDOUT as normal. And like β€” if you're expecting the response to not be printable text in your terminal's character encoding, you're gonna wanna redirect the command's output to a file or a hexdump program. trust. πŸ‘‘

Options may follow the command:

  • --content=<string>, -c <string> β€” passes the string value as the request body content and sets the Content-Length request header to its size.
  • --cookie=<string>, -C <string> β€” string values of the form name=value get passed as request cookies. Can appear multiple times. πŸͺ
  • --header=<string>, -H <string> β€” string values of the form Name: value get passed as request headers. Can appear multiple times. And if you provide the same header name more than once, the values get joined with commas β€” which is only valid for certain headers, so watch out. πŸ™ˆ
  • --verbose, -v β€” includes response CGI headers (or HTTP headers in NPH mode) in the output, before the response content. It's enabled automatically for head.

πŸ’– COMPARISON TO CGI.PM πŸ’–

So traditionally, the CGI module (affectionately called CGI.pm, to tell it apart from the CGI protocol itself) has been the thing people use to write Perl CGI scripts. This module fills a similar need, but there are a whole bunch of interface differences you need to be aware of. let's get into it πŸ’…

  • There is no CGI::Tiny object constructor. The object is accessible within the cgi block, it only reads request data from the environment once it's accessed, and it makes sure a valid response gets rendered β€” so no gateway errors, even if an exception happens or you exit prematurely. main character reliability honestly ✨
  • Instead of global variables like $CGI::POST_MAX, global behavior settings get applied to the CGI::Tiny object inside the cgi block.
  • Exceptions inside the cgi block are handled by default by rendering a server error response and emitting the error as a warning. You can customize this with set_error_handler.
  • Request parameter accessors in CGI::Tiny are not context sensitive, because context sensitivity can lead to surprising behavior and vulnerabilities <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-1572>. param, query_param, body_param, and upload always return a single value; you have to use param_array, query_param_array, body_param_array, and upload_array to retrieve multi-value parameters.
  • CGI::Tiny's param accessor is also not method-sensitive β€” it accesses either query or body request parameters with the same behavior regardless of request method. And query and body request parameters can be accessed separately with query_param and body_param respectively. 🌸
  • CGI::Tiny's param accessor only retrieves text parameters. Uploaded files and their metadata are accessed with upload and related methods.
  • CGI::Tiny decodes request parameters to Unicode characters automatically, and render/render_chunk provide methods to encode response content from Unicode characters to UTF-8 by default.
  • In CGI.pm, response headers must be printed manually before any response content gets printed, or you end up with malformed responses. In CGI::Tiny, the render or render_chunk methods are used to print response content, and they automatically print response headers the first time they're called. redirect responses are handled by render too.
  • In CGI::Tiny, a custom response status is set by calling set_response_status before the first render or render_chunk β€” and it only requires the status code, because it'll add the appropriate human-readable status message itself. slay.
  • Response setters are distinct methods from request accessors in CGI::Tiny. content_type, header, and cookie are used to access request data, and set_response_type, add_response_header, and add_response_cookie are used to set response headers for the pending response before the first call to render or render_chunk.
  • CGI::Tiny does not provide any HTML generation helpers, because that functionality is much better implemented by other robust implementations on CPAN; see "Templating" in CGI::Tiny::Cookbook.
  • CGI::Tiny does not do any implicit encoding of cookie values or the Expires header or cookie attribute. See "Cookies" in CGI::Tiny::Cookbook for examples of encoding and decoding cookie values. The epoch_to_date convenience function is provided to render appropriate Expires date values. πŸ“

There are a number of alternatives to CGI.pm, but ngl they don't sufficiently address the design issues. Primarily: none of them gracefully handle exceptions or failure to render a response, and several of them have no features for rendering responses at all. πŸ’€

  • CGI::Simple shares all of the interface design problems of CGI.pm, though it does not reimplement the HTML generation helpers.
  • CGI::Thin is ancient and only implements parsing of request query or body parameters β€” without decoding them to Unicode characters.
  • CGI::Minimal has context-sensitive parameter accessors, and only implements parsing of request query/body parameters (without decoding them to Unicode characters) and uploads.
  • CGI::Lite has context-sensitive parameter accessors, and only implements parsing of request query/body parameters (without decoding them to Unicode characters), uploads, and cookies.
  • CGI::Easy has a robust interface, but it pre-parses all request information.

⚠️ CAVEATS ⚠️

CGI is an extremely simplistic protocol, and it relies particularly on the global state of environment variables and the STDIN and STDOUT standard filehandles. CGI::Tiny does not stop you from messing with these interfaces directly β€” but bestie, it may result in confusion. 😭

CGI::Tiny eschews certain sanity checking for performance reasons. For example, Content-Type and other header values set for the response should only contain ASCII text with no control characters, but CGI::Tiny does not verify this (though it does verify they do not contain newline characters, to protect against HTTP response splitting). so like, be careful. πŸ™ˆ

Field names and filenames in multipart/form-data requests do not have a well-defined escape mechanism for special characters, so CGI::Tiny will not attempt to decode these names from however the client passes them β€” aside from set_multipart_form_charset. For best compatibility, form field names should be ASCII without double quotes or semicolons. πŸ’…


πŸ› BUGS πŸ›

Report any issues on the public bugtracker. please and thank you 🫢


πŸ‘‘ AUTHOR πŸ‘‘

Dan Book <dbook@cpan.org>


This software is Copyright (c) 2021 by Dan Book.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

πŸ¦‹ SEE ALSO πŸ¦‹

CGI::Alternatives, Mojolicious, Dancer2


and that's the whole page, bestie!! πŸ’– this little gem is CGI::Tiny(3pm), documented for perl v5.38.2, and this version was dated 2024-06-15. go forth and write the cutest, safest little CGI scripts. periodt βœ¨πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from