[英]PHP not triggering Fatal Error when memory_limit reached
我有一个基本页面,我尝试出现Fatal Error, Out of memory
显示Fatal Error, Out of memory
消息,但是什么也没发生,脚本没有错误,PHP 7.1.9没有suhosin。
ini_set("memory_limit", 100); //100 bytes.
echo "Memory Limit Bytes " . ini_get("memory_limit") . PHP_EOL;
echo "Script peak memory usage " . memory_get_peak_usage() . PHP_EOL;
不输出致命错误。
Memory Limit Bytes 100
Script peak memory usage 386960
The End
您正在使用PHP的一个非常麻烦的领域。 问题是,一旦您的PHP进程内存不足,游戏就会结束。 由于致命错误触发脚本终止,因此不会引发异常。
根据我的经验,这里最好的选择是使用register_shutdown_function()注册一个回调,该回调将检查error_get_last()并处理由@(关闭)运算符或ini_set('display_errors',false)忽略的有问题的代码。
如果在发生此错误时需要执行重要的清理代码,则注册关闭功能是不够的。 一种方法是在您的PHP进程横盘整理时在可以释放的地方分配一些紧急内存。
<?php
ini_set("memory_limit", 400000); //100 bytes
ini_set('display_errors', false);
error_reporting(-1);
echo("start");
echo "Memory Limit Bytes " . ini_get("memory_limit") . PHP_EOL;
echo "Script peak memory usage " . memory_get_peak_usage() . PHP_EOL;
// This storage is freed on error (case of allowed memory exhausted)
$memory = str_repeat('*', 100000);
echo("2");
set_error_handler(function($code, $string, $file, $line){
throw new ErrorException($string, null, $code, $file, $line);
});
register_shutdown_function(function(){
global $memory;
$memory = null;
$error = error_get_last();
if(null !== $error)
{
echo 'Caught at shutdown';
}
});
try
{
$a = '';
for ($i=0; $i<=10000000; $i++) {
$a .= '1';
}
echo("done");
}
catch(\Exception $exception)
{
echo 'Caught in try/catch';
}
?>
查看这篇讨论PHP的内存处理(以及其他内容)的文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.