Tim Hogard's Quick and Dirty Perl CGI

Tim Hogard's Quick and Dirty Perl CGI

I write a quite a few simple web cgi programs and I tend to write them in Perl. The common way that most books and web examples make use of a few typical Perl modules but they are overkill for most projects and if you need speed, you don't have time to load the modules.

This is my basic perl cgi (download link):

#!/usr/bin/perl -Tw

use strict;
use warnings;

# tims cgi ver 3.52  16/Mar/2025
my %cgi;	# html cleaned vars go into here so > becomes >
my %cgi_;	# all vars go in here without change
my %cookie;	# cookies go in here

$|=1; # set to unbuffered output for long running scripts

#look at what the user set to us in the URL
my $query=$ENV{QUERY_STRING} || "";
#POST data over writes what came in on the URL
if ( defined($ENV{'CONTENT_LENGTH'}) && $ENV{'CONTENT_LENGTH'} > 0 ) {
	read(STDIN, $query, $ENV{'CONTENT_LENGTH'});
}

my @q=split(/&/,$query);

foreach (sort(@q)) {
        my ($name, $value) = split(/=/, $_);

        $name  =~ tr/+/ /;      # a space used to be encoded as a plus
        $value =~ tr/+/ /;
        # get rid of the hex we were sent
        $name  =~ s/%([A-F0-9][A-F0-9])/pack("C", hex($1))/gie;
        $value =~ s/%([A-F0-9][A-F0-9])/pack("C", hex($1))/gie;	
        $cgi_{$name}=$value;	# $cgi_ has xss unfriendly values
	# the following are to stop cross site scripting but
	# they make it hard to check for & < > ( or ) in values
	# the values below should be &,>,<,( or ) on the left side and
	# &amp;amp; &amp;gt lt #40 or #41 on the right side
	$value =~ s/&/&amp;/gi;
	$value =~ s/>/&gt;/gi;
	$value =~ s/</&lt;/gi;
        $value =~ s/\(/&#40;/gi;
        $value =~ s/\)/&#41;/gi;
        $cgi{$name}=$value;
        #print "$name = $value \n";
}

#if cookies are going to be used
if($ENV{HTTP_COOKIE}) {
        #HTTP_COOKIE=var=val; var2=val2
        my(@x)=split(/;/,$ENV{HTTP_COOKIE});
        foreach(@x) {
                my($var,$val)=split(/=/);
		$cookie{$var}=$val;
		#print "$name = $value<br>\n";
	}
}

#if path info is used 
#my $path_info=$ENV{'PATH_INFO'};

print "Content-type: text/html\n\n";

foreach(sort(keys(%cgi))) {
	print "$_=$cgi{$_}<br>\n";
}
foreach(sort(keys(%cookie))) {
	print "$_=$cookie{$_}<br>\n";
}



All single letter variables can be optimized out but I tend to use it this way as it's easier for others to understand.

The PATH_INFO allows you to put info in the url handed to the cgi such as
http://server/cgi-bin/script/argument/somevalue.

Version 3.47 Sep 16 2006 was to reduce cross site scripting issues.
Version 3.51 Jul 29 2021 was to clean up perl code
Version 3.52 Mar 16 2025 was to fix up the format of this page


Back to Tim's Homepage Back to current subject Related Links thogard@abnormal.com
 This page was last updated Sunday, 16-Mar-2025 09:08:05 UTC Copyright 2000-2020 thogard™ is a trademark of Tim Hogard