What does it mean when my CGIs fail with "Premature end of script headers"?
It means just what it says: the server was expecting a complete set of HTTP headers (one or more followed by a blank line), and didn't get them.
The most common cause of this problem is the script dying before sending the complete set of headers, or possibly any at all, to the server. To see if this is the case, try running the script standalone from an interactive session, rather than as a script under the server.
If you get error messages, this is almost certainly the cause of the "premature end of script headers" message. Even if the CGI runs fine from the command line, remember that the environment and permissions may be different when running under the web server. The CGI can only access resources allowed for the User and Group specified in your Apache configuration. In addition, the environment will not be the same as the one provided on the command line, but it can be adjusted using the directives provided by mod_env.
The second most common cause of this (aside from people not
outputting the required headers at all) is a result of an interaction
with Perl's output buffering.
To make Perl flush its buffers after each output statement, insert
the following statements around the print or write statements that send
local ($oldbar) = $|;
$cfh = select (STDOUT);
$| = 1;
# print your HTTP headers here
$| = $oldbar;
This is generally only necessary when you are calling external programs from your script that send output to stdout, or if there will be a long delay between the time the headers are sent and the actual content starts being emitted. To maximize performance, you should turn buffer-flushing back off (with $| = 0 or the equivalent) after the statements that send the headers, as displayed above.
If your script isn't written in Perl, do the equivalent thing for whatever language you are using (e.g., for C, call fflush() after writing the headers).
Another cause for the "premature end of script headers" message are the RLimitCPU and RLimitMEM directives. You may get the message if the CGI script was killed due to a resource limit. (Rarely the case)
In addition, a configuration problem in suEXEC, mod_perl, or another third party module can often interfere with the execution of your CGI and cause the "premature end of script headers" message. (Rarely the case)
Other Perl Cgi Script problems.