Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 43 Β· Modules and Errors

CGI and Web Scripts

Learn how Perl CGI scripts work: the request-response cycle, environment variables, headers, parsing GET and POST data by hand, escaping output and modern alternatives.

Perl powered much of the early web through CGI, the Common Gateway Interface. CGI is a simple contract between a web server and a program: the server runs your script once per request, hands it the request details, and sends back whatever the script prints. New sites rarely use plain CGI today, but the model is a good way to understand how every web framework works underneath, and a lot of production Perl still runs on it.

How CGI works

flowchart LR
    B["Browser"] --> S["Web server"]
    S -->|"environment variables + stdin"| P["Perl script"]
    P -->|"headers, blank line, body on stdout"| S
    S --> B

The server is the gateway: it starts your script for each request and relays its output.

The rules are tiny:

  • Input: request metadata arrives in environment variables (REQUEST_METHOD, QUERY_STRING, CONTENT_LENGTH, CONTENT_TYPE, REMOTE_ADDR, HTTP_USER_AGENT). For POST, the body arrives on standard input.
  • Output: print the HTTP headers, then one blank line, then the body. Headers end with \r\n.
  • The script must be executable and start with a line such as #!/usr/bin/perl.

The smallest script

PERL
#!/usr/bin/perl
use v5.36;

print "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
print "Hello from Perl\n";
say "Your address: ", $ENV{REMOTE_ADDR} // 'unknown';

The Content-Type header is required. Forgetting the blank line after the headers is the classic cause of a "500 Internal Server Error" with a log line like "malformed header from script".

Reading form data

A GET form puts fields in QUERY_STRING as name=Ann&city=Oslo. Spaces become + and other special characters become %XX hex codes. Decoding that by hand shows what a library does for you:

PERL
#!/usr/bin/perl
use v5.36;

sub url_decode($s) {
    $s =~ tr/+/ /;
    $s =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ge;
    return $s;
}

sub parse_query($qs) {
    my %p;
    for my $pair (split /&/, $qs // '') {
        my ($k, $v) = split /=/, $pair, 2;
        next unless defined $k && length $k;
        $p{ url_decode($k) } = url_decode($v // '');
    }
    return %p;
}

sub html_escape($s) {
    my %map = ('&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&#39;');
    $s =~ s/([&<>"'])/$map{$1}/g;
    return $s;
}

my %param = parse_query($ENV{QUERY_STRING});
my $name  = html_escape($param{name} // 'stranger');

print "Content-Type: text/html; charset=UTF-8\r\n\r\n";
print "<p>Hello, $name!</p>\n";

Requesting ?name=Ann+%3Cb%3E prints <p>Hello, Ann &lt;b&gt;!</p>, and with no query string it greets stranger. For a POST request, read exactly CONTENT_LENGTH bytes from standard input and parse them the same way:

PERL
my $len = $ENV{CONTENT_LENGTH} // 0;
read(STDIN, my $body, $len);
my %form = parse_query($body);

Never trust CONTENT_LENGTH blindly: cap it (for example at 100,000 bytes) before reading, or one request can use all your memory.

Security rules for web scripts

  • Escape every value you print into HTML. Printing raw input is how cross-site scripting (XSS) happens; the html_escape above is the minimum.
  • Never build shell commands or SQL by pasting input into strings. Use list-form system and database placeholders. See Security for taint mode, which Perl can enforce with -T on the shebang line.
  • Validate with a strict regex and an allow-list, not a block-list.
  • Do not expose error details to visitors; log them instead.

Modern alternatives

Plain CGI starts a new Perl process per request, which is slow under load. Real projects use a library or framework:

  • CGI.pm was the classic helper (parsing, cookies, HTML helpers). It left the core distribution in Perl 5.22, so you install it from CPAN. It is fine for old code, but new code usually avoids it.
  • PSGI/Plack is the modern standard: a script becomes a function that takes an environment hash and returns a response, and the same app runs under many servers.
  • Mojolicious, Dancer2 and Catalyst are full frameworks built on that idea.
  • FastCGI and mod_perl keep the interpreter alive between requests.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. How does a CGI script receive the query string of a GET request?

    The web server passes request metadata, including QUERY_STRING, as environment variables. Only POST bodies arrive on standard input.
  2. 2. What must come between the headers and the body of a CGI response?

    Headers end with an empty line (CRLF CRLF). Without it the server reports a malformed header.
  3. 3. Why escape user input before printing it into HTML?

    Unescaped input can inject script tags into the page. Replacing & < > and quotes with entities stops that.
  4. 4. Which technology is the modern standard interface between Perl web apps and servers?

    PSGI (used by Plack, Mojolicious and Dancer2) replaced plain CGI as the common interface.

Summary

  • CGI runs your script once per request: input via environment variables and stdin, output via stdout.
  • Print headers, a blank line, then the body.
  • Decode + and %XX yourself or use a library, and always escape output.
  • Prefer PSGI frameworks for new projects.

Next, learn how to check your work in Testing in Perl.