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:


#!/usr/bin/perl -Tw

use strict;
use warnings;

# tims cgi ver 3.51  29/Jul/2021
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 to stop cross site scripting but
	# they make it hard to check for & < > ( or ) in values
	$value =~ s/&/&/gi;
	$value =~ s/>/>/gi;
	$value =~ s/\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{$_}
\n"; } foreach(sort(keys(%cookie))) { print "$_=$cookie{$_}
\n"; }
All single letter variables can be optimized out but I tend to useit this way as its 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.


Back to Tim's Homepage Back to current subject Related Links thogard@abnormal.com
 This page was last updated Tuesday, 29-Jun-2021 00:09:36 UTC Copyright 2000-2020 thogard™ is a trademark of Tim Hogard