Debugging internal server errors (premature end of script headers) part 8
Die statementsIf your script opens files like this:
|open (F, "myfile.txt");
then you need to do something about it! If at any stage the script can't open the file, this can lead to problems. Either a script can sit there hanging if it can't open and write to a file, or you can spend ages trying to work out exactly why your script isn't doing what it should be.
Change the above code to:
|open (F, "myfile.txt") || die "cannot open myfile.txt";
The script will then error with the message:
|cannot open myfile.txt at test.cgi line 31.|
If you use '$!' in your statement:
|open (F, "myfile.txt") || die "cannot open myfile.txt $!";
...it will print out why it died
|cannot open myfile.txt No such file or directory at test.cgi line 31.|
$! contains the error returned by the server and you use it in your die statement to print the error out.
Use the same die statement with sendmail as well - if there's problems, it will stop the script hanging and return the error.
|open(MAIL, "| /usr/bin/sendmail -t") || die "Unable to open sendmail. $!";|
If there's a problem with sendmail, or the path to sendmail is wrong - it will end the script and return the error:
|Unable to open sendmail. No such file or directory at test.cgi line 311.|
It is recommended that you go right through your script and put 'die' statements in wherever the script tries to open up a file. It does two things: lets you know that there's a problem, as well as killing off the execution of the script instead of letting it keep trying forever to open a file that doesn't exist.