Send a 500 Internal Server Error header with PHP.

This is a short guide on how to send a 500 Internal Server Error header to the client using PHP. This is useful because it allows us to tell the client that the server has encountered an unexpected condition and that it cannot fulfill the request.

Below, I have created a custom PHP function called internal_error.

//Function that sends a 500 Internal Server Error status code to
//the client before killing the script.
function internal_error(){
    header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);
    echo '<h1>Something went wrong!</h1>';
    exit;
}

When the PHP function above is called, the script’s execution is halted and “Something went wrong!” is printed out onto the page.

Furthermore, if you inspect the HTTP headers with your browser’s developer console, you will see that the function is returning a 500 Internal Server Error status code:

500 Internal Server Error

Google’s Developer Tools showing the 500 Internal Server Error status that was returned.

To send the 500 status code, we used PHP’s header function like so:

//Send a 500 status code using PHP's header function
header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);

Note that we used the SERVER_PROTOCOL variable in this case because the client might be using HTTP 1.0 instead of HTTP 1.1. In other examples, you will find developers making the assumption that the client will always be using HTTP 1.1.

This is not the case.

The problem with PHP is that it doesn’t always send a 500 Internal Server Error when an exception is thrown or a fatal error occurs.

This can cause a number of issues:

  1. It becomes more difficult to handle failed Ajax calls, as the server in question is still responding with a 200 OK status. For example: The JQuery Ajax error handling functions will not be called.
  2. Search engines such as Google may index your error pages. If this happens, your website may lose its rankings.
  3. Other HTTP clients might think that everything is A-OK when it is not.

Note that if you are using PHP version 5.4 or above, you can use the http_response_code function:

//Using http_response_code
http_response_code(500);

Far more concise!