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

I'm using the CGI libraries:
use CGI qw/:standard/; use CGI::Validate;
And I'm trying to find a way to be able to parse a get/post request into variables, as well as log the get/post request. Currently, I'm using a series of:
my $variable = param( "var" ) || "OFF";
And it works great for parsing the variables.
After the variable parsing, to log the Get/Post request, I'm using:
if ($ENV{'REQUEST_METHOD'} eq "GET") { $request = $ENV{'QUERY_STRING'}; } if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $request,$ENV{'CONTENT_LENGTH'}) || warn "Could not get query\n"; } ##Then Save $request to file.
Works great for get requests, I can parse the variables and log the get request. But with Post requests, I can parse the variables, but the post request doesn't get logged (cause it's already been read in by the variables and there is nothing to readin in). When I move the get/post log function to the top of the param calls, Get still works, and the Post logger works, but I don't get to parse the variables if it's a post cause it's been read into $request.

So using the same functionality as the above with the param() call, is there a better way to do this so that I can both log the full request, AND parse the variables? I was originally doing all of this by hand, but was persuaded into moving to CGI.pm from the board, and am curious if there is a one liner to tell cgi.pm to save the request, AND keep it for parsing..
thanks!

Replies are listed 'Best First'.
Re: Log a Post Request
by brian_d_foy (Abbot) on Jan 23, 2006 at 19:32 UTC

    Are you just trying to record what parameters (and values) that your script saw? Do you care if you see the original HTTP request?

    Once you let CGI parse the parameters, everything you need is in the CGI object. Record what you get before you do anything else.

    use CGI; my $query = CGI->new; # reads overthing log( $query ); #....the rest of your program sub log { my $q = shift; foreach my $param ( $q->param ) { #... however you want to log things my @values = $q->param( $param ); } }
    Update: a stray "s" made it into my code, and it has been hunted down and terminated.
    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review

      foreach my $param ( $q->params )
      should be
      foreach my $param ( $q->param )

Re: Log a Post Request
by ikegami (Patriarch) on Jan 23, 2006 at 19:36 UTC

    You could log it first, and replace STDIN with a in-memory file (open(local *STDIN, '<', \$raw_data)) but the following might be sufficient:

    use URI::Escape qw( uri_escape_utf8 ); foreach my $key ($cgi->param()) { foreach my $val ($cgi->param($key)) { printf("%s=%s\n", uri_escape_utf8($key), uri_escape_utf8($val), ); } }

    You could also look at CGI's save method.