How to send 500 Internal Server Error error from a PHP script

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.

Edit

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?


Solution 1:

header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);

Solution 2:

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).