How to handle POST request to PERL from html

喜你入骨 提交于 2019-12-04 21:19:43
use CGI qw( );
my $cgi = CGI->new();
my $json = $cgi->param('POSTDATA');

All that you need to know is in RFC3875 — the specification for The Common Gateway Interface Version 1.1

Essentially, the CGI program is passed information about the incoming request message through both the environment variables and the STDIN input channel. If the CGI program is a Perl one then the environment variables can be accessed through the built-in hash %ENV, which will contain a fixed set of values such as REQUEST_METHOD (which will normally be HEAD, GET, or POST) or CONTENT_LENGTH

The body of the message is delivered to the CGI program via its STDIN channel, and the value of CONTENT_LENGTH indicates how many bytes should be read from the channel to fetch the complete message body

In the case of a POST message that represents form input from the browser, REQUEST_METHOD will, obviouly, be POST; CONTENT_TYPE will be application/x-www-form-urlencoded (unless one of the form fields is a file upload); and CONTENT_LENGTH will hold the number of bytes of data in the request message body, which is the amount of data that the CGI program should read from STDIN. This should be done using read STDIN instead of the usual <STDIN> because the server may not put an EOF after the valid body data. Your code will look like

my $bytes_read = read STDIN, my $form_data, $ENV{CONTENT_LENGTH}

after which the form data will be saved in $form_data in the same format as the query portion of a GET URL (that's what the urlencoded part of the content type means)

If you need to know any more about what the CGI environment provides and expects then take a look at the RFC that I have linked above. It's fairly straightforward to read

Pavel

Borodin's answer says all. Basically, you don't need the CGI.pm overhead:

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

my %form;
if ($ENV{REQUEST_METHOD} eq 'POST') {
    read(STDIN, my $form_data, $ENV{CONTENT_LENGTH})
      or die "$!\n";

    # URL decode
    chomp($form_data);
    $form_data =~ tr/+/ /;
    $form_data =~ s/%([a-f0-9][a-f0-9])/chr(hex($1))/egi;

    foreach (split /&/, $form_data) {
        # trim spaces
        s/^\s+|\s+$//g;

        # get the URL param
        my($key, $value) = split(/=/, $_, 2);
        $form{$key} = $value || '';
    }
}

a dichotomy

HTML <input type="text" name="email" />

CGI my $email = $form{email};

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!