CGI Programming, Something Useful

Browser Based Content

'browser.pl' in Perl

#!/usr/local/bin/perl

use CGI;

if( $ENV{'HTTP_USER_AGENT'} =~ /Mozilla\/3.0/ )
{
  $document = "/js11page.html";
}
else
{
  $document = "/nojspage.html";
}

# This subroutine comes from CGI
print $query->header( "text/html" );

# Think about how you would use this script for
# your entire site!!!
$htmldoc = $document;

if( open( HTML, "< $htmldoc" ) )
{
  while( <HTML> )
  {
    print;
  }
  close( HTML );
}
else
{
  # From Reuven M Lerner's March 1997 Linux Journal article
  &log_and_die( "Tried to open $htmldoc" );
}

exit 0;


Error Handling

'log_and_die.pl' in Perl

#!/usr/local/bin/perl5 -w

  use strict;       # Check our syntax strictly
  use diagnostics;  # Tell us how to fix mistakes
  use CGI;          # Import the CGI module
  use CGI::Carp;

  # Create an instance of CGI
  my $query = new CGI;


sub log_and_die
  {
  	# Get arguments
	my $string = shift;

	# Begin the HTML
	print $query->start_html(-title => "Error");

	# Give a message
	print "<P>Sorry, but this program has";
	print "encountered an error. The system ";
	print "administrator has been ";
	print "informed</P>\n";

	print "<P>Would you like to return to the ";
	print "<a href=\"/\">home page</a>?\n";

	# End the HTML
	print $query->end_html();

  # Now die with the error message
  die $string;
}

This code used with permission from Reuven M. Lerner and The Linux Journal


A Better Mailto Form

'mailto.pl' in Perl

#!/usr/local/bin/perl

require "cgi-lib.pl";

# Flow control begins here
$message_body = undef;
$error = 0;

# Load the input variables
&ReadParse( *input );

# Print the HTTP header
print &PrintHeader;

# Set up the message body
$message_body .= "Name:        $input{'name'}\n" if( "$input{'name'}" ne undef );
$message_body .= "Email:       $input{'email'}\n" if( "$input{'email'}" ne undef );
$message_body .= "Comments:\n$input{'comments'}\n";

# Print the top of the page
print "<HTML><HEAD><TITLE>Your title here</TITLE></HEAD><BODY>\n";

# Print the body of the page
if( "$input{'comments'}" eq undef )
{
  print "<P>You have not entered a comment.</P>";
  print "<P>Please press the back button on your browser and complete ";
  print "the form.</P>";
  $error = 1;
}
else
{
  # This could be bad!!!
  print "<P><B><FONT SIZE=\"+1\">Thanks $input{'name'}.</FONT></B></P>\n";
}


# Print the bottom of the page
print "</BODY></HTML>\n";

if( ! $error )
{
open( MAIL, "|/usr/lib/sendmail -t -n" );
print MAIL <<EndOfMessage
From: mailto form
To: userid\@host.com
Subject: mailto form

$message_body
EndOfMessage
;
exit;
}


Last Modified: 17 February 1997

St. Louis Unix Users Group - Linux SIG