CGI::T...ookbook(3pm)
π CGI::Tiny::Cookbook(3pm) π
okay hi bestie, welcome to CGI::Tiny::Cookbook(3pm) β User Contributed Perl Documentation β¨ this is the cookbook and it's giving advanced CGI::Tiny usage, but make it a whole vibe. grab a boba, we're doing this. π§π¦
πΈ NAME πΈ
CGI::Tiny::Cookbook β recipes for advanced CGI::Tiny usage π
π DESCRIPTION π
okay so CGI::Tiny is a minimal interface to the CGI protocol. like, it does the bare minimum and honestly that's the whole point, no cap. but bestie β the common tasks? those can totally be simplified with the use of other CPAN modules and techniques. and that's literally what this whole thing is. π«Ά
π RECIPES π
π¦ Dependencies
okay so real talk: CGI scripts that have dependencies (and yes, CGI::Tiny itself counts as one of those π) must be run using the perl that those dependencies were actually installed to. and they need access to any nonstandard library installation locations, like local::lib or Carton. no shortcuts, bestie.
now here's the tricky part: CGI scripts run in the CGI server's environment, which is usually different from your user's environment. so because of that, this means that:
- the CGI script shebang should be an absolute path to the appropriate
perlexecutable. absolute. not vibes-based. π₯
#!/usr/bin/perl
#!/opt/perl/bin/perl
#!/home/youruser/perl5/perlbrew/perls/perl-5.34.0/bin/perl
- nonstandard library locations where your deps live must either be added to the
"PERL5LIB"environment variable in the CGI server's environment, or added within the CGI script itself β like withliborlib::relative. pick your fighter π
# Apache
SetEnv PERL5LIB /home/youruser/perl5/lib/perl5
# Within CGI script
use lib '/home/youruser/perl5/lib/perl5';
# Relative to CGI script
use lib::relative 'local/lib/perl5';
π¦ Fatpacking
App::FatPacker can be used to pack CGI::Tiny, plus any other pure-perl dependencies, into a CGI script β so you can deploy it to other systems without having to install the deps over there. as a bonus (iconic behavior honestly), this means the script doesn't have to load those modules separately from disk on every single execution. slay. β
just keep in mind: the script will have to be repacked to update those dependencies, and CGI scripts greatly benefit from efficient XS tools which cannot be packed this way. sad but true. π
$ fatpack pack script.source.cgi > script.cgi
and if you wanna pack in optional modules β like JSON support for Perls older than 5.14:
$ fatpack trace --use=JSON::PP script.source.cgi
$ fatpack packlists-for $(cat fatpacker.trace) > packlists
$ fatpack tree $(cat packlists)
$ fatpack file script.source.cgi > script.cgi
π§ JSON
CGI::Tiny has built-in support for parsing and rendering JSON content with JSON::PP. but listen β CGI scripts that deal with JSON content will greatly benefit from installing Cpanel::JSON::XS version 4.09 or newer for efficient encoding and decoding. and guess what? it'll be used automatically if it's available. the way it just knows. π₯
π¨ Templating
HTML and XML responses are most easily managed with templating. a bunch of CPAN modules provide this capability, and here are two faves:
Text::Xslate is an efficient template engine designed for HTML/XML with built-in disk caching. obsessed.
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Text::Xslate;
use Data::Section::Simple 'get_data_section';
cgi {
my $cgi = $_;
# from templates/
my $tx = Text::Xslate->new(path => ['templates']);
# or from __DATA__
my $tx = Text::Xslate->new(path => [get_data_section]);
my $foo = $cgi->query_param('foo');
$cgi->render(html => $tx->render('index.tx', {foo => $foo}));
};
__DATA__
@@ index.tx
<html><body><h1><: $foo :></h1></body></html>
Mojo::Template is a lightweight HTML/XML template engine in the Mojo toolkit. also iconic.
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Mojo::Template;
use Mojo::File 'curfile';
use Mojo::Loader 'data_section';
cgi {
my $cgi = $_;
my $mt = Mojo::Template->new(auto_escape => 1, vars => 1);
my $foo = $cgi->query_param('foo');
# from templates/
my $template_path = curfile->sibling('templates', 'index.html.ep');
my $output = $mt->render_file($template_path, {foo => $foo});
# or from __DATA__
my $template = data_section __PACKAGE__, 'index.html.ep';
my $output = $mt->render($template, {foo => $foo});
$cgi->render(html => $output);
};
__DATA__
@@ index.html.ep
<html><body><h1><%= $foo %></h1></body></html>
π Files
modules like Path::Tiny and MIME::Types can help with file responses. but heads up bestie β be aware that Perl and some operating systems work with filenames in encoded bytes (usually UTF-8), but this module works with parameters in Unicode characters. so non-ASCII filenames make things trickier. it's giving encoding nightmare but we persist. π
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Path::Tiny;
use MIME::Types;
use Unicode::UTF8 qw(encode_utf8 decode_utf8);
cgi {
my $cgi = $_;
my $filename = $cgi->query_param('filename');
unless (length $filename) {
$cgi->set_response_status(404)->render(text => 'Not Found');
exit;
}
# get files from public/ next to cgi-bin/
my $public_dir = path(__FILE__)->realpath->parent->sibling('public');
my $encoded_filename = encode_utf8 $filename;
my $filepath = $public_dir->child($encoded_filename);
# ensure file exists, is readable, and is not a directory
unless (-r $filepath and !-d _) {
$cgi->set_response_status(404)->render(text => 'Not Found');
exit;
}
# ensure file path doesn't escape the public/ directory
unless ($public_dir->subsumes($filepath->realpath)) {
$cgi->set_response_status(404)->render(text => 'Not Found');
exit;
}
my $basename = decode_utf8 $filepath->basename;
my $mime = MIME::Types->new->mimeTypeOf($basename);
$cgi->set_response_type($mime->type) if defined $mime;
$cgi->set_response_disposition(attachment => $basename)->render(file => $filepath);
};
πͺ Cookies
okay so cookie values should only consist of ASCII characters, and they may not contain any control characters, space characters, or the characters "",;\". that's the rule, no exceptions. π€ more complex strings can be encoded to UTF-8 and base64 for transport β and honestly? that's the move.
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Unicode::UTF8 qw(decode_utf8 encode_utf8);
use MIME::Base64 qw(decode_base64 encode_base64);
cgi {
my $cgi = $_;
my $value = $cgi->param('cookie_value');
unless (defined $value) {
my $cookie = $cgi->cookie('unicode');
$value = decode_utf8 decode_base64 $cookie if defined $cookie;
}
if (defined $value) {
my $encoded_value = encode_base64 encode_utf8($value), '';
$cgi->add_response_cookie(unicode => $encoded_value, Path => '/');
$cgi->render(text => "Set cookie value: $value");
} else {
$cgi->render(text => "No cookie value set");
}
};
and data structures can be encoded to JSON and base64 for transport. yup, we're doing that too. π
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Cpanel::JSON::XS qw(decode_json encode_json);
use MIME::Base64 qw(decode_base64 encode_base64);
cgi {
my $cgi = $_;
my $key = $cgi->param('cookie_key');
my $hashref;
if (defined $key) {
$hashref->{$key} = $cgi->param('cookie_value');
} else {
my $cookie = $cgi->cookie('hash');
$hashref = decode_json decode_base64 $cookie if defined $cookie;
$key = (keys %$hashref)[0] if defined $hashref;
}
if (defined $hashref) {
my $encoded_value = encode_base64 encode_json($hashref), '';
$cgi->add_response_cookie(hash => $encoded_value, Path => '/');
$cgi->render(text => "Set cookie hash key $key: $hashref->{$key}");
} else {
$cgi->render(text => "No cookie value set");
}
};
π Sessions
regardless of which session mechanism you go with, login credentials should only be sent over HTTPS, and passwords should be stored on the server using a secure one-way hash β like with Crypt::Passphrase. this is not a suggestion bestie, this is the law. π₯
π‘οΈ Basic authentication
<https://en.wikipedia.org/wiki/Basic_access_authentication> has historically been used to provide a simplistic login session mechanism which relies on the client to send the credentials with every subsequent request in that browser session. however β it does not have a reliable logout or session expiration mechanism. so like, it's giving "fine for a demo" energy, ngl. π
Basic authentication can be handled by the CGI server itself (e.g. Apache <https://httpd.apache.org/docs/2.4/howto/auth.html>), which restricts access to a directory or location to authenticated users, and passes AUTH_TYPE and REMOTE_USER with the authenticated CGI requests. that's the easy path fr fr.
if you wanna instead handle Basic authentication directly in the CGI script, you may need to configure the CGI server to forward the "Authorization" header (e.g. Apache <https://stackoverflow.com/q/17018586/5848200>), because it is commonly stripped from the CGI request. rude, honestly. π€
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use MIME::Base64 'decode_base64';
use Unicode::UTF8 'decode_utf8';
sub verify_password { my ($user, $pass) = @_; ... }
cgi {
my $cgi = $_;
my $authed_user;
if (defined(my $auth = $cgi->header('Authorization'))) {
if (my ($hash) = $auth =~ m/^Basic (\S+)/i) {
my ($user, $pass) = split /:/, decode_utf8(decode_base64($hash)), 2;
$authed_user = $user if verify_password($user, $pass);
}
}
unless (defined $authed_user) {
$cgi->add_response_header('WWW-Authenticate' => 'Basic realm="My Website", charset="UTF-8"');
$cgi->set_response_status(401)->render;
exit;
}
$cgi->render(text => "Welcome, $authed_user!");
};
a more sophisticated and modern login session mechanism is to store a session cookie in the client, associated with a server-side session stored in a file or database. login credentials only need to be validated once per session, and subsequently the session ID stored in the cookie will be sent by the client with each request. this type of session can be ended by expiring the session cookie and invalidating the session data on the server. chef's kiss π
some HTTP session management modules exist on CPAN, but the author has not yet discovered any that are suitable for use with CGI::Tiny. in lieu of a generalized mechanism, session data can be stored to and retrieved from your database of choice manually. iykyk. π
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Text::Xslate;
use Data::Section::Simple 'get_data_section';
sub verify_password { my ($user, $pass) = @_; ... } sub store_new_session { my ($user) = @_; ... } sub get_session_user { my ($session_id) = @_; ... } sub invalidate_session { my ($session_id) = @_; ... }
cgi { my $cgi = $_;
my $tx = Text::Xslate->new(path => [get_data_section]);
my ($authed_user, $session_id); if ($cgi->path eq '/login') { if ($cgi->method eq 'GET' or $cgi->method eq 'HEAD') { $cgi->render(html => $tx->render('login.tx', {login_failed => 0})); exit; } elsif ($cgi->method eq 'POST') { my $user = $cgi->body_param('login_user'); my $pass = $cgi->body_param('login_pass'); if (verify_password($user, $pass)) { $session_id = store_new_session($user); $authed_user = $user; } else { $cgi->render(html => $tx->render('login.tx', {login_failed => 1})); exit; } } } elsif (defined($session_id = $cgi->cookie('myapp_session'))) { if ($cgi->path eq '/logout') { invalidate_session($session_id); # expire session cookie $cgi->add_response_cookie(myapp_session => $session_id, 'Max-Age' => 0, Path => '/', HttpOnly => 1); $cgi->render(redirect => $cgi->script_name . '/login'); exit; } else { $authed_user = get_session_user($session_id); } }
unless (defined $authed_user) { $cgi->render(redirect => $cgi->script_name . '/login'); exit; }
set/refresh session cookie
$cgi->add_response_cookie(myapp_session => $session_id, 'Max-Age' => 3600, Path => '/', HttpOnly => 1);
$cgi->render(text => "Welcome, $authed_user!"); };
__DATA__ @@ login.tx <html> <head> <title>Login</title> </head> <body> <form method="post"> <input type="text" name="login_user" placeholder="Username"> <input type="password" name="login_pass" placeholder="Password"> <button type="submit">Login</button> </form> : if $login_failed { <p>Login failed</p> : } </body> </html>
---
## π Logging π
okay so bestie, logging in CGI-land is lowkey simpler than you'd think. CGI scripts can usually log errors straight to `STDERR` with the `warn` function, and then just vibe and let the CGI server log them to a file for you. <pink>BUT</pink> β and this is the important bit β you will likely need to encode errors to UTF-8 if you expect them to contain non-ASCII text. don't skip that step, it's giving mojibake otherwise π
Minimal loggers like Log::Any can also be used to redirect errors and warnings to a file or other logging mechanism specific to the CGI script, encode them to bytes automatically, and also log debugging information when the log level is set to `debug`. just make sure the CGI server has permission to create and write to the logging target β if it can't write there, no logs, no cap. π«Ά
#!/usr/bin/perl use strict; use warnings; use utf8; use CGI::Tiny; use Log::Any; use Log::Any::Adapter {category => 'cgi-script'}, # only log our category here File => '/path/to/log/file.log', binmode => ':encoding(UTF-8)', log_level => $ENV{MYCGI_LOG_LEVEL} || 'info';
my $log = Log::Any->get_logger(category => 'cgi-script');
local $SIG{__WARN__} = sub { my ($warning) = @_; chomp $warning; $log->warn($warning); };
cgi { my $cgi = $_;
$cgi->set_error_handler(sub { my ($cgi, $error, $rendered) = @_; chomp $error; $log->error($error); });
only logged if MYCGI_LOG_LEVEL=debug set in CGI server environment
$log->debugf('Method: %s, Path: %s, Query: %s', $cgi->method, $cgi->path, $cgi->query);
my $number = $cgi->param('number'); die "Excessive number\n" if abs($number) > 1000; my $doubled = $number * 2; $cgi->render(text => "Doubled: $doubled"); };
---
## πΊοΈ Routing πΊοΈ
Web applications use routing to serve multiple types of requests from one application. Routes::Tiny can be used to organize this with CGI::Tiny, using `REQUEST_METHOD` and `PATH_INFO` (which is the URL path after the CGI script name). that's the whole trick β `PATH_INFO` is literally just "everything after `script.cgi` in the URL", so your app can have real β¨routesβ¨ instead of a pile of `if` statements. obsessed.
#!/usr/bin/perl use strict; use warnings; use utf8; use CGI::Tiny; use Routes::Tiny;
my %dispatch = ( foos => sub { my ($cgi) = @_; my $method = $cgi->method; $cgi->render(text => "$method foos"); }, get_foo => sub { my ($cgi, $captures) = @_; my $id = $captures->{id}; $cgi->render(text => "Retrieved foo $id"); }, put_foo => sub { my ($cgi, $captures) = @_; my $id = $captures->{id}; $cgi->render(text => "Stored foo $id"); }, );
cgi { my $cgi = $_;
my $routes = Routes::Tiny->new;
/script.cgi/foo
$routes->add_route('/foo', name => 'foos');
/script.cgi/foo/42
$routes->add_route('/foo/:id', method => 'GET', name => 'get_foo'); $routes->add_route('/foo/:id', method => 'PUT', name => 'put_foo');
if (defined(my $match = $routes->match($cgi->path, method => $cgi->method))) { $dispatch{$match->name}->($cgi, $match->captures); } else { $cgi->set_response_status(404)->render(text => 'Not Found'); } };
---
## π AUTHOR π
Dan Book <dbook@cpan.org>
---
## π COPYRIGHT AND LICENSE π
This software is Copyright (c) 2021 by Dan Book.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
---
## π¦ SEE ALSO π¦
- <cyan>**CGI::Tiny**</cyan>
---
and that's a wrap bestie!! π this iconic little cookbook came to you from **perl v5.38.2**, dated **2024-06-15**, and it's filed under the majestic name <rainbow>**CGI::T...ookbook(3pm)**</rainbow> β go forth and slay your CGI scripts, you absolute legend πβ¨
π¦ where this page comes from
- debian trixie: libcgi-tiny-perl 1.003-1 Β· Artistic-2.0
- ubuntu resolute: libcgi-tiny-perl 1.003-1 Β· Artistic-2.0
- ubuntu stonking: libcgi-tiny-perl 1.003-1 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms