Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send POST and GET data to a Perl CGI script via the command line?

Tags:

I am trying to send a get or a post through a command-line argument. That is test the script in the command line before I test through a browser (the server has issues). I tried searching online, and I suppose I was probably using incorrect terminology because I got nothing. I know this is possible because I saw someone do it. I just don't remember how it was done.

Thanks! :)

like image 478
Parris Avatar asked Feb 08 '10 19:02

Parris


2 Answers

To test a CGI program from the command line, you fake the environment that the server creates for the program. CGI.pm has a special offline mode, but often I find it easier not to use because of the extra setup I need to do for everything else my programs typically expect.

Depending on the implementation of your script, this involves setting many environment variables, which you can do from a wrapper script that pretends to be the server:

 #!/bin/bash   export HTTP_COOKIE=...  export HTTP_HOST=test.example.com  export HTTP_REFERER=...  export HTTP_USER_AGENT=...  export PATH_INFO=  export QUERY_STRING=$(cat query_string);  export REQUEST_METHOD=GET   perl program.cgi 

If you're doing this for a POST request, the environment is slightly different and you need to supply the POST data on standard input:

 #!/bin/bash   export CONTENT_LENGTH=$(perl -e "print -s q/post_data/");  export HTTP_COOKIE=...  export HTTP_HOST=test.example.com  export HTTP_REFERER=...  export HTTP_USER_AGENT=...  export PATH_INFO=...  export QUERY_STRING=$(cat query_string);  export REQUEST_METHOD=POST   perl program.cgi < post_data 

You can make this as fancy as you need and each time you want to test the program, you change up the data in the query_string or post_data files. If you don't want to do this in a shell script, it's just as easy to make a wrapper Perl script.

like image 92
brian d foy Avatar answered Oct 11 '22 23:10

brian d foy


Are you using the standard CGI module?

For example, with the following program (notice -debug in the arguments to use CGI)

#! /usr/bin/perl  use warnings; use strict;  use CGI qw/ :standard -debug /;  print "Content-type: text/plain\n\n",       map { $_ . " => " . param($_) . "\n" }       param; 

you feed it parameters on the command line:

$ ./prog.cgi foo=bar baz=quux Content-type: text/plain  foo => bar baz => quux

You can also do so via the standard input:

$ ./prog.cgi (offline mode: enter name=value pairs on standard input; press ^D or ^Z when done) foo=bar baz=quux ^D Content-type: text/plain  foo => bar baz => quux
like image 21
Greg Bacon Avatar answered Oct 11 '22 22:10

Greg Bacon