Saving a Form to a File or Mail Pipe
Problem
Your CGI script needs to save or mail the entire form contents to a file.
Solution
To store a form, use the CGI module’s
save_parameters
function or save method, which take a filehandle
argument. You can save to a file:
# first open and exclusively lock the file open(FH, ">>/tmp/formlog") or die "can't append to formlog: $!"; flock(FH, 2) or die "can't flock formlog: $!"; # either using the procedural interface use CGI qw(:standard); save_parameters(*FH); # with CGI::save # or using the object interface use CGI; $query = CGI->new(); $query->save(*FH); close(FH) or die "can't close formlog: $!";
Or, save to a pipe, such as one connected to a mailer process:
use CGI qw(:standard); open(MAIL, "|/usr/lib/sendmail -oi -t") or die "can't fork sendmail: $!"; print MAIL <<EOF; From: $0 (your cgi script) To: hisname\@hishost.com Subject: mailed form submission EOF save_parameters(*MAIL); close(MAIL) or die "can't close sendmail: $!";
Discussion
Sometimes all you want to do with form data is to save it for later
use. The save_parameters function and
save method in CGI.pm write form parameters to an
open filehandle. That filehandle can be attached to an open file
(preferably one opened in append mode and locked, as in the
solution), or to a pipe whose other end is a mail program.
File entries are stored one per line as
variable=value pairs, with any funny characters URL-escaped. Each record is separated by a line with a single equals sign. These are ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access