[rochester-pm-list] Quick Question...

Bob Walton bwalton at rochester.rr.com
Tue Dec 7 21:25:18 CST 1999


Fred Edmister wrote:
> 
>         I have my script running from the command prompt now, and was wondering if
> someone could give me an idea on how to read info from a form instead... (I
> know there is plenty of information on this, and I have a couple of books
> as well, but it's kinda a "hurry rush" thing from upper level...)  If
> anyone can help, it would be great!!  I just have a couple fields to read
> from a form, the rest I can figure out... (do they just keep the name they
> have in the form when sent? {ie, can I just assume that when the "SUBMIT"
> button is clicked, that the "Name" field on the form will become $name in
> the script})  Thank you anyone who can help!!
> 
>         Fred

Fred, for light-duty CGI, you can use the following little
subroutine:

#sub to read CGI input and return it as a hash
sub read_input
{
    local ($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);
        $name =~ tr/+/ /;
        $name =~ s/%(..)/pack("C", hex($1))/eg;
        $value =~ tr/+/ /;
        $value =~ s/%(..)/pack("C", hex($1))/eg;
	while(exists($FORM{$name})){$name++;} #handle multiple instances
        $FORM{$name} = $value;
    }
    %FORM;
}

Call it like:

     %form=&read_input;

and use the returned parameters like:

     $paramvalue1=$form{paramname1};

In the above case, "paramname1" is the name given in the
name="paramname1" field of the <input ...> tag in the
HTML <form>.  Note that if a name appears more than once
in your HTML form and is sent more than once, the
instances after the first instance will be identified by
the name with the automagical string increment operator
applied, once for each appearance of the name.  If you
don't like that, just remove the "while" line from the
sub, in which case only the last instance will be returned.

This sub will decode either GET or POST requests.  You'll 
have to set up your web server so it will run Perl CGI scripts.

For serious CGI work, use CGI;

The little subroutine above can make your script a bit quicker to
run than using the CGI module.  But it doesn't even come close
in terms of goodies.  Best wishes.
-- 
Bob Walton



More information about the Rochester-pm mailing list