ARTICLE AD BOX
I've already read several possible SO duplicates such as this and particularly this where hipertrtacker says register_shutdown_function can catch fatal errors and Peter Mortensen showed code very similar to my own.
Can somebody please help explain why the following stripped down code is not calling my shutdown() function when it terminates? Have I made an unintentional coding error somewhere? (Note: The actual shutdown() function in the real script logs debug_backtrace() and other stuff to find out where I got to when I get a server timeout error)
I'm deliberately setting timeout to 1s, then looping until the script terminates due to a timeout error.
<?php function shutdown() { error_log("\r\n" . 'shutdown called', 3, "./x_log.txt") ; } set_time_limit(1); register_shutdown_function("shutdown"); error_log("\r\n" . "Starting" , 3, "./x_log.txt"); for(;;) { error_log("\r\n" . "looping" , 3, "./x_log.txt"); } error_log("\r\n" . "Ending" , 3, "./x_log.txt"); ?>Expected behaviour
The file x_log.txt will contain the word 'Starting' followed by about 85,000 lines with 'looping', followed by a line with 'shutdown called'. There should be no line with the word 'Ending' as we terminated due to a deliberate error before we got there. The error_log will show the line 'PHP Fatal error: Maximum execution time of 1 second exceeded in /home/aaaaaa/public_html/x.php on line 11Actual behaviour
The file x_log.txt contains the word 'Starting' followed by about 85,000 lines with 'looping' but nothing else. The error_log shows the line 'PHP Fatal error: Maximum execution time of 1 second exceeded in /home/aaaaaa/public_html/x.php on line 11Problem It seems that the function shutdown() is not being called to write 'shutdown called' to the log.
Question What am I doing wrong and how can I can I make this code snippet to work correctly and call the shutdown function, even when terminating due to an error?
Environment
I'm calling x.php from a browser using the url https://www.aaaaaa.tech/x.php The server is a shared server (so I can't access php.ini or any other admin stuff) I'm using php version 8.1.33 The output of get_defined_functions() shows that register_shutdown_function() is available to me