I need to send "500 Internal Server Error" from an PHP script under certain conditions. The script is supposed to be called by a third party app. The script contains a couple of die("this happend")
statements for which I need to send the 500 Internal Server Error
response code instead of the usual 200 OK
. The third party script will re-send the request under certain conditions which include not receiving the 200 OK
response code.
Second part of the question: I need to setup my script like this:
<?php custom_header( "500 Internal Server Error" ); if ( that_happened ) { die( "that happened" ) } if ( something_else_happened ) { die( "something else happened" ) } update_database( ); // the script can also fail on the above line // e.g. a mysql error occurred remove_header( "500" ); ?>
I need to send 200
header only after the last line has been executed.
A side question: can I send strange 500 headers such as these:
HTTP/1.1 500 No Record Found HTTP/1.1 500 Script Generated Error (E_RECORD_NOT_FOUND) HTTP/1.1 500 Conditions Failed on Line 23
Will such errors get logged by the webserver?
Check the error_reporting , display_errors and display_startup_errors settings in your php. ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it).
In most cases, a 500 Internal Server Error is due to an incorrect permission on one or more files or folders. In most of those cases, an incorrect permission on a PHP and CGI script is to blame. These should usually be set at 0755 (-rwxr-xr-x).
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:
http_response_code(500);
I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.
To answer your follow-up question, the HTTP 1.1 RFC says:
The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.
That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With