Html – how to pass a variable from an HTML form to a perl cgi script

cgihtmlperl

I would like to use an HTML form to pass a variable to Perl CGI script so that I can process that variable, and then print it out on another HTML page.

Here is my HTML code: http://jsfiddle.net/wTVQ5/.

Here is my Perl CGI script to links the HTML. Here is the way I would like to do it (since it uses less lines and probably more efficient).

#!/usr/bin/perl
use warnings; use strict;
use CGI qw( :standard);
my $query = CGI->new;

# Process an HTTP request
my $user = $query->param('first_name');

# process $user... for example:
my $foo = "Foo";
my $str = $user . $foo;

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "</head>";
print "<body>";
print "<h2>Hello $str - Second CGI Program</h2>";
print "</body>";
print "</html>";

1;

Here's a way I read from a tutorial and makes more sense to me:

#!/usr/bin/perl
use warnings; use strict;

my ($buffer, @pairs, $pair, $name, $value, %FORM);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST") {
   read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
   $buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%(..)/pack("C", hex($1))/eg;
    $FORM{$name} = $value;
}
my $user = $FORM{first_name};

# process $user... for example:
my $foo = "Foo";
my $str = $user . $foo;

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>Hello - Second CGI Program</title>";
print "</head>";
print "<body>";
print "<h2>Hello $str - Second CGI Program</h2>";
print "</body>";
print "</html>";

1;

Both of these don't work properly BTW. When I click on the submit button on the HTML page, it just links me to the script instead of passing the variable, processing it, and printing out the HTML page.

Best Answer

this line:

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

should be:

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

or better:

print $query->header;

Also, ensure your web server was well configurated for CGI. And, if you have enough time, use a modern web application approach, there are many frameworks that may be better than CGI (Dancer, Mojolicious, OX, ...)