These kinds of errors are the most difficult to handle in PHP:
PHP Fatal error: Out of memory (allocated XXX) (tried to allocate XXX bytes)…
Because no memory is available there isn’t a lot PHP can do. When I discussed PHP and HTTP status codes last month, I covered how if text is sent to the browser PHP sends a default code of 200 OK
. So, out of memory errors can be missed or mishandled.
One thing you can do though is register a shutdown function; this is a function called after your script has finished (calling die
, exit
and your script coming to an end all trigger a shutdown). If you stop errors being displayed (display_errors = 0
) as well you can at least output a better HTTP status code when you run out of memory (on a AJAX call, for example).
Note that because PHP has run out of memory you shouldn’t count on being able to write a log file, etc as this all takes memory.
Here is an example:
register_shutdown_function(function() {
$error = error_get_last();
if ($error['type'] === E_ERROR && headers_sent() === false) {
http_response_code(500);
}
});
