In the concluding article in the Perl 101 series, everythingyou've learnt so far is put to the test when you develop some real-worldCGI applications - a counter, a guest book and a form mailer.
Now, you need to have the contents of this form emailed to
you every time someone submits it. Here's the Perl script that you'll need:
#! /usr/bin/perl
# mailform.cgi - email form contents to webmaster
# define a variable that accepts a value from the form
$in;
# assign values to the variable depending on form METHOD
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$in = $ENV{'QUERY_STRING'};
}
else {
$in = <STDIN>;
}
# fix URL-encoded strings
$in =~ s/\+/ /g;
# all variables are passed to the script as name-value pairs separated by &
# split the input string on the basis of &
@detail = split (/&/, $in);
# open mail pipe
open (MAIL,"|/usr/sbin/sendmail -t");
print MAIL "To: <webmaster\@yoursite.com>\n";
print MAIL "From: Feedback Form Mailer\n";
print MAIL "Subject: Feedback on your site\n\n";
print MAIL "Here is the result of your feedback form.\n\n";
foreach $details(@detail)
{
%details = split (/=/, $details);
while (($name, $value) = each %details)
{
print MAIL "$name: $value\n";
}
}
close MAIL;
print "Content-Type: text/html\n\n";
print "<html><body><center><font face=Arial size=+1>Thank you for your
feedback!</font></center></body></html>";
If you take a close look, you'll see that this script is very
similar to the one we used when writing the guestbook. Here too, we've accepted form data as a single string, split it on the basis of the &, and then further split it against the = separator.
Next, we've opened a file handle - except that we haven't actually opened a file, but a UNIX "pipe", which allows you to "pipe" data to a UNIX command. In this case, the command is the sendmail program, which is used to deliver email. sendmail needs a few basic headers - the To:, From: and Subject: fields, which we've provided, followed by each name-value pair in the body of the message. Once all the pairs are exhausted, the handle is closed and the mail is sent out.
And here's the sample mail that you'll see:
To: webmaster@yoursite.com
From: Feedback.Form.Mailer
Subject: Feedback on your site
Here is the result of your feedback form.
who: johndoe
email: johndoe@cyberspace.com
address: the web
age: 28
And that's about it for this time. We hope you enjoyed this
series of tutorials - write in and tell us what you'd like to see next. And till next time, stay healthy!
This article copyright Melonfire 2000. All rights reserved.