Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I'm learning perl, as this question will aptly demonstrate! I'm trying to make a cgi form that will present a text box to be filled in with text, then once posted, it will display the output of that post on either the same, or a new page (all on the same cgi url). Is this possible or do I need a seperate html page to post from then a cgi to process it? If some one could just point me to an example (yep, already tried google, but it doesn't like the way I'm asking it questions today) Input form view:
print "Content-type: text/html <body> <form action="/cgi-bin/posttest.cgi" method="POST"> <textarea name="content" cols=40 rows=4>Enter data here. </textarea> <input type="submit" value="Process"> </form> </body> </html>
Output:
print "Content-type: text/html <body> print "you posted $string"; ...

Replies are listed 'Best First'.
Re: simple form post question
by shmem (Chancellor) on Dec 13, 2007 at 07:15 UTC
    You could have posted the full script. Anyways:
    #!/usr/bin/perl use CGI; use strict; my $q = CGI->new; my $string = $q->param('content'); # the posted string. $string =~ s/\r?\n$//s; # remove trailing CRLF if ($string =~ /foo/) { # decide what to do depending on input print $q->redirect('http://host.tdl/some/other/uri'); } else { print $q->header,$q->start_html; if($string) { # print "<p>You posted: $string\n"; # <-- bad # what oxone said below - avoid XSS attacs print "<p>You posted: ",$q->escapeHTML($string),"\n"; # <-- be +tter } else { print <<EOH; <form action="/cgi-bin/posttest.cgi" method="POST"> <textarea name="content" cols=40 rows=4>Enter data here. </textarea> <input type="submit" value="Process"> </form> EOH } print $q->end_html; }

    update: fixed XSS vulnerability. Thanks, oxone.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      By the by, this is also a great example of how to open up your site to cross-site scripting vulnerabilities.

      It's always a bad idea to take some CGI input, then display it right back to the browser. The user may enter HTML tags, Javascript etc. which might then disrupt your returned page.

      I'd recommend always doing this if displaying back submitted data into the browser:

      print $cgi->escapeHTML($string);

      This 'escapes' any meaningful characters such as angle brackets, so the browser will just display them literally.

Re: simple form post question
by ikegami (Patriarch) on Dec 13, 2007 at 07:36 UTC
    You're missing a blank line between the header and the body of the response.
Re: simple form post question
by Anonymous Monk on Dec 13, 2007 at 09:52 UTC