PHP 捕获最大执行时间错误
PHP 中有没有一种方法可以在达到最大执行时间时捕获致命错误并给用户一个更好的消息?
Is there a way in PHP to trap the fatal error when the max execution time is reached and give the user a better message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
阅读此处的前两个答案后,我必须自己测试
register_shutdown_function()
——我认为它不会运行。毕竟,一旦没有更多内存或执行时间已过,用户函数如何运行?我很惊讶地发现关闭函数确实会运行,即使是在 OOM 情况下或超出执行时间时也是如此。概念验证:测试内存限制:
输出:
测试执行时间:
输出:
请注意,要让消息在 PHP 错误输出之前显示,您必须完全禁用 PHP 错误输出。无论如何,这对于生产站点来说是最佳实践。
After reading the first two answers here, I had to test
register_shutdown_function()
myself -- I didn't think it'd run. After all, how can a user function run once there's no more memory, or execution time has elapsed? I was surprised to learn that shutdown functions do run, even in an OOM situation, or when execution time has been exceded. Proof of concept:To test memory limit:
Output:
To test execution time:
Output:
Note that, to get your message to display before PHP's error output, you'd have to disable PHP's error output entirely. Which is best practice for a production site anyway.
尝试在执行文件后设置“完成”标志并注册一个关闭函数来检查该标志是否已定义
Try setting a "Done" flag after the execution of a file and registering a shutdown function that will check if that flag is defined
我原来的答案不起作用,因为您无法捕获致命错误。如果您仍然想阅读它,请检查修订历史记录。
我唯一的猜测是您可以使用
register_shutdown_function
。在脚本开始时设置一个变量,在脚本成功完成后清除它。编写一个函数来检查该变量并对其进行操作(如果它仍然设置),然后使用register_shutdown_function
应用该函数http://php.net/manual/en/function.register-shutdown-function.php
My original answer won't work, as you can't catch a fatal error. If you want to read it anyway, check the revision history.
My only guess is that you could use
register_shutdown_function
. Set a variable at the start of the script, clear it when the script has completed successfully. Write a function that checks that variable and acts on it if it's still set, then apply the function usingregister_shutdown_function
http://php.net/manual/en/function.register-shutdown-function.php
如果没有办法从 API 级别捕获错误,则 PHP 引擎应该能够在发生致命错误时将内存转储到硬盘上,就像 Windows 在看到“蓝屏”时所做的那样。
If there's no way to trap the error from the API level, the PHP engine should be able to dump the memory on hdd whenever a fatal error occurs, like what Windows does when you see a 'blue screen'.