Don’t call me DOM

12 July 2004

Testing CGI scripts with QUERY_STRING, in PHP

Filed under:

When developing a CGI script and before putting on the production server, you need to test it; to catch runtime errors, but more generally, to check if you get the expected result depending on the parameters.

To emulate a GET request without setting up a Web server, the easiest method is probably to set the QUERY_STRING and REQUEST_METHOD environment variables and run the script through its interpreter, e.g. REQUEST_METHOD="GET" QUERY_STRING="foo=bar" php4 filename.php.

Well, this used to work till recently – I assumed it broke with PHP 4.3 release; nowadays, the php4 executable comes in two flavours: the CLI and the CGI SAPI; the former is designed to be use out of Web context, so isn’t much relevant to this case.

The latter is the executable called by a Web server properly configured to handle PHP as CGI (e.g. not as a module in Apache); so the command line given above should work, since that’s what the CGI specification describes. But it doesn’t.

For security reasons, the CGI version of PHP4 can’t be called directly as is, otherwise it barks:

Security Alert!

The PHP CGI cannot be accessed directly.

This PHP CGI binary was compiled with force-cgi-redirect enabled. This means that a page will only be served up if the REDIRECT_STATUS CGI variable is set, e.g. via an Apache Action directive.

So, there is probably a solution involving the DOCUMENT_ROOT or REDIRECT_STATUS environment variables, but I still haven’t found it. In the meantime, I’ve put the following code snippets at the top of my core include files in my PHP projects:


if (empty($_GET)) {
  parse_str($_ENV['QUERY_STRING'],$_GET);
}

… and now, I’m happy again.

2 Responses to “Testing CGI scripts with QUERY_STRING, in PHP”

  1. Dominique Hazaël-Massieux Says:

    You can apparently now with PHP pass GET arguments using the same convention as perl and python, with /usr/lib/cgi-bin/php4 script.php foo=bar.

  2. How to pass query string parameters to the PHP binary? - PHP Solutions - Developers Q & A Says:

    […] mentioned in Don’t call me DOM » Testing CGI scripts with QUERY_STRING, in PHP, you may have to use parse_str to parse environment variables passed via cli mode – example […]

Picture of Dominique Hazael-MassieuxDominique Hazaël-Massieux (dom@w3.org) is part of the World Wide Web Consortium (W3C) Staff; his interests cover a number of Web technologies, as well as the usage of open source software in a distributed work environment.