PHP如何抑制file_get_contents引发的错误?

时间:2017-12-05 15:07:04

标签: php

尝试仅限制file_get_contents的错误,但这两种方法都不起作用..还有另外一种方法吗?

$data=@file_get_contents('invalid');

try { $data=@file_get_contents('invalid'); } catch($e Exception) { echo "error"; }

1 个答案:

答案 0 :(得分:0)

修复问题,不要隐藏它们。

错误,警告和通知应该被修复而非隐藏(“被压制”)。

对于您的情况,您只需检查is_readable

function getFile(string $filename = 'invalid')
{
    if (!is_readable($filename)) {
        return false;
    }

    return file_get_contents($filename);
}

$fileContents = getFile('maybevalid');
if (false !== $fileContents) {
    // success
} else {
    // couldn't read
}