防止 false 上的内部错误file_get_contents



我想使用以下方法来检测文件是否存在,但是在这种情况下会触发警告。当file_get_contents不返回 false 时,它可以正常工作。

$nothing = "http://www.google.com/bababababa.doc";
if (false === file_get_contents($nothing,0,null,0,1)) {
    echo "File Not Found";
} else {
    echo "File Found";
}

首先,我假设您只想从日志中隐藏此错误,因为您当然display_errors在生产服务器上关闭了此错误。

您可以使用@错误抑制运算符隐藏错误,但这是一条糟糕的开始之路。相反,您希望定义一个错误处理程序:

<?php
// define the custom handler that just returns true for everything
$handler = function ($err, $msg, $file, $line, $ctx) {return true;}
$nothing = "http://www.google.com/bababababa.doc";
// update the error handler for warnings, keep the old value for later
$old_handler = set_error_handler($handler, E_WARNING);
// run the code
$result = file_get_contents($nothing);
// go back to normal error handling
set_error_handler($old_handler);
if (false === $result) {
    echo "File Not Found";
} else {
    echo "File Found";
}

最新更新