How to Return an HTTP 500 Code on Any Error, No Matter What
In PHP APIs, the default behavior is often the opposite of what you need. By default, if a script encounters a fatal error or triggers a warning after output has started, PHP serves an HTML error page but still returns an HTTP status code of 200 OK. For an authentication endpoint where a 200 response strictly means "success," this is unacceptable. You need to flip the logic: only return 200 when the token is approved; every other scenarioâwhether it's a missing header, a database deadlock, or a syntax errorâmust result in a 500 Internal Server Error or a 403 Forbidden.
Achieving this requires moving beyond standard error_reporting() settings. While setting E_ALL & ~E_DEPRECATED and using set_error_handler() is the first step, it cannot catch fatal errors like E_ERROR, E_PARSE, or E_CORE_ERROR in all contexts without careful configuration, and it certainly cannot handle the "output started" scenario where you need to hijack the response stream.
The most robust way to enforce a 500 status on any unhandled error is to utilize PHP's built-in error handling mechanisms at the application level before any output occurs. You can register a custom error handler using set_error_handler() that checks for specific error levels. However, this alone won't solve the problem if a fatal error (like calling a function that doesn't exist) occurs after headers have been sent or if the script crashes completely.
To guarantee that any failure results in a 500 response, you should wrap your critical logic in a try-catch block and ensure no output is generated until the HTTP headers are set. This architectural pattern prevents PHP from emitting its default HTML error pages. Instead of relying on php.ini directives like display_errors = Off, which only suppresses the output but not necessarily the status code in all versions, you must explicitly handle the response lifecycle.
Here is a practical implementation strategy using a global try-catch block and explicit header management:
<?php
// Ensure no output happens before headers are sent
ob_start();
try {
// Your authentication logic here
if (authenticate($credentials)) {
http_response_code(200);
echo json_encode(['status' => 'approved']);
} else {
http_response_code(403);
echo json_encode(['status' => 'forbidden']);
}
} catch (\Exception $e) {
// Catchable exceptions become 500s automatically if headers aren't sent yet
http_response_code(500);
echo json_encode(['status' => 'server_error', 'message' => 'An unexpected error occurred.']);
}
// If we are here, it means the script finished without a fatal crash.
// However, if a fatal error (E_ERROR) occurs, PHP will still die.
The catch block handles exceptions, but fatal errors bypass the try-catch entirely. To intercept fatal errors and force a 500, you need to register a custom handler for specific fatal error types using set_error_handler() or, more effectively, rely on the fact that if your code is structured correctly, fatal errors should be minimized or handled via register_shutdown_function().
A more comprehensive approach involves using set_exception_handler alongside set_error_handler. In the shutdown function, you can inspect if an error occurred and set the headers accordingly before outputting JSON. However, this is tricky because once a fatal error triggers a crash, the script execution stops immediately unless caught by the shutdown handler.
To ensure that even fatal errors result in a 500 status code, you must configure PHP to not display errors as HTML and instead rely on your custom handlers. This requires setting display_errors to Off and log_errors to On in your environment configuration. When display_errors is off, PHP will not automatically output the HTML error page. If a fatal error occurs after headers are sent, you get a "Cannot modify header information" warning, which PHP defaults to a 500.
If you need this behavior at the web server level, Apache's .htaccess or Nginx configuration can act as a fallback. For example, in Apache, you can use ErrorDocument 500 /error.php to serve a custom page, but forcing a specific status code for all unhandled errors usually requires application-level control. The most reliable method remains ensuring your PHP script explicitly sets the status code before any echo statement and using ob_clean() or ob_flush() carefully if you need to manipulate the output buffer.
For production environments where strict API contracts are required, consider leveraging frameworks like Laravel. In such a framework, global exception handlers manage these scenarios elegantly by default, ensuring that any uncaught exception results in a specific JSON response with a 500 status code, preventing raw HTML leaks. If you are building a custom API, mimic this behavior by centralizing your error handling logic and never relying on PHP's default output mechanisms.