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

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

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Implementing Custom HTTP Status Codes in PHP Error Handling

When building APIs or scripts consumed by third-party applications, the standard die() function often produces output that is too verbose or generic for upstream consumers. By default, a fatal error in PHP might result in a 500 Internal Server Error with an unhelpful stack trace, but if you need to explicitly control the HTTP status code based on specific business logic conditions—such as distinguishing between "no record found" and a generic script failure—you must handle headers manually.

The core mechanism relies on intercepting the response lifecycle before any output is sent to the client. In PHP, once output buffering has started or a response header has been sent, you cannot change the status code anymore. Therefore, your custom logic must execute prior to any echo statements or even simple whitespace that might trigger output buffering in some configurations.

To implement this pattern, you should define helper functions like custom_header() and remove_header() to encapsulate the raw PHP calls. This keeps your main script readable while adhering to strict protocol requirements.

<?php
function custom_header($status) {
    $code = substr($status, 0, 3);
    $message = substr($status, 4);
    
    // Set the status code explicitly
    http_response_code((int)$code);
    
    // Ensure no headers have been sent yet
    if (headers_sent()) {
        die('Cannot send response header: headers already sent.');
    }

    header("HTTP/1.1 $status");
}

function remove_header($name) {
    // In PHP, we generally cannot remove the Status Line once set via http_response_code()
    // or header(), but this function is useful if you need to clear other headers 
    // before switching back to a 200 status in a different context.
    // For the specific use case of changing from 500 to 200, you must set the new status immediately.
}

Your main script logic should flow strictly linearly. You set the initial error header at the very top. If any condition fails—whether it is that_happened or something_else_happened—you terminate execution immediately. The third-party application will detect the 500 status and decide whether to retry.

<?php
custom_header("500 Internal Server Error");

if (that_happened) {
    die("that happened");
}

if (something_else_happened) {
    die("something else happened");
}

// Update database
update_database();

// If we reach here, everything was successful.
// We must now send the 200 OK header before any output.
header("HTTP/1.1 200 OK");

A critical pitfall in this approach is the handling of the status code transition. You cannot simply call remove_header("500") and then expect to send a new status later without re-setting it. In PHP, the HTTP status line is set once at the beginning of the response. If you set HTTP/1.1 500 Internal Server Error, that is the status that will be sent unless you explicitly call http_response_code(200) again before any output occurs. However, if headers have already been sent (e.g., because a previous die() was called or whitespace was echoed), subsequent header modifications will fail.

Regarding your question about custom error messages in the status line:

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

Technically, the HTTP specification does not forbid custom phrases in the status line for non-standard codes, but standard clients and proxies often only display the numeric code or a generic text. More importantly, web servers and PHP's error logging mechanisms typically log the status code (500) rather than the specific text provided in the header unless configured to do so. If your third-party app parses the response body for specific strings like "No Record Found," sending that string in the header might be redundant or confusing if the client expects it in the JSON/XML body. It is generally better practice to keep the status line standard (e.g., 500 Internal Server Error) and place the specific error context in the response body.

Finally, ensure that your update_database() function does not trigger a fatal error before you have a chance to send the final 200 header. If a MySQL error occurs within that function, PHP will likely emit an uncaught exception or call die(), which would revert the status back to 500 (or whatever error code the framework defaults to). To maintain the strict flow where only the final line triggers a 200, your database layer should ideally throw exceptions that you can catch and translate into specific exit codes before any output is generated.

Our network