PHP fopen 错误捕获

函数2020.04.05发生异常,导致程序异常退出php进程

function down($filename){
	$handle = fopen($filename, "r"); 
	$contents = ""; 
	do { 
		$data = fread($handle, 8192); 
		if (strlen($data) == 0) { 
			break; 
		} 
		$contents .= $data; 
	} while(true); 
	fclose($handle); 	
	return $contents;
}

状态查询:nginx 自身有个日志问题
/home/wwwlogs/nginx_error.log

2020/04/02 00:59:45 [alert] 17320#0: *3376022 http request count is zero while closing request, client: 50.70.90.27, server: 0.0.0.0:443

读取的时候

这个错误因为读取不到文件,发生错误,程序异常然后exit了。

无效的办法1.改动的异常捕获

try{
		$handle = fopen($filename, "r"); 
	}catch(Exception $e){
		print $e->getMessage();
	}

失败,根本没有异常弹出

Warning: fopen(https://java-er.com/no.php): failed to open stream: php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /www/autotest.php on line 33
 
Warning: fread() expects parameter 1 to be resource, boolean given in /www/autotest.php on line 39
 
Warning: fclose() expects parameter 1 to be resource, boolean given in /www/autotest.php on line 45

无效的办法2. 强行报错测试

register_shutdown_function("errorCheck");
 
function errorCheck(){
 
    $error=error_get_last();
	 print_r($error);
}
 
function test(Array $a){
    echo 1;
}
 
//强行报错
test(123);

发现可以报错

合并到代码里
用到了这里,不好用。说明这个强行报错的办法,只能监测到系统级别错误,无法获取warning

3. 增加全局报错,依然无效

error_reporting(E_ALL);

换成 E_WARNING 也无效

4. set_error_handler

 //error handler function
function customError($errno, $errstr)
 { 
 echo "<b>Error:</b> [$errno] $errstr";
 }
 
//set error handler
set_error_handler("customError");
php autotest.php

2020-04-05 11:55:56

<b>Error:</b> [2] fopen(https://java-er.com/no.php): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
####<b>Error:</b> [2] fread() expects parameter 1 to be resource, boolean given<b>Error:</b> [2] fclose() expects parameter 1 to be resource, boolean given2020-04-05 11:55:59 
<b>Error:</b> [2] fopen(https://java-er.com/no.php): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
####<b>Error:</b> [2] fread() expects parameter 1 to be resource, boolean given<b>Error:</b> [2] fclose() expects parameter 1 to be resource, boolean given^C

set_error_handler 可以正确的打印,我想补获的错误,程序在下载一个不存在文件,或者出错的情况下。就可以监控了。

后记:set_error_handler感觉在触发底层线程,当我在customError里试图修改一个php的全局变量,无效。只好把warning的信息都写到一个文件里 wwww/log/err.log


This entry was posted in PHP and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/php-fopen-error-catch/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.
2020.03.24 评论已经全局关闭,有事加QQ聊天