使用try catch块无法捕获PHP file_get_contents错误 - php

我正在尝试使用file_get_contents函数获取图像,但它给出了错误。为了处理错误,我使用了try catch块,但是它没有捕获到错误并且失败了。

我的代码:

try {
     $url = 'http://wxdex.ocm/pdd.jpg'; //dummy url
     $file_content = file_get_contents($url);
}
catch(Exception $e) {
     echo 'Error Caught';           
}

错误:

Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: No such host is known
Warning: file_get_contents(http://wxdex.ocm/pdd.jpg): failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.

注意::我能够在遥控器上获取任何其他有效的图像URL。

参考方案

try/catch不起作用,因为warning不是exception

您可以尝试使用此代码,以便也可以捕获警告。

//set your own error handler before the call
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
    throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);

try {
    $url = 'http://wxdex.ocm/pdd.jpg';
    $file_content = file_get_contents($url);
} catch (Exception $e) {
    echo 'Error Caught'; 
}

//restore the previous error handler
restore_error_handler();

PHP:file_get_contents($ loc)失败 - php

我只是将一个项目从localhost移到了我的远程服务器上,并且注意到我的某些脚本停止工作了。最重要的是依赖file_get_contents()从另一个脚本中获取JSON值的脚本。PHP版本是5.2.4allow_url_fopen开启 警告:file_get_contents() [function.file-get-contents]:php_netw…

vfsstream:file_get_contents()无法打开流:stream_open调用失败 - php

我已经设置了vfsstream块设备,并且尝试在其上调用file_get_contents()。但是,对vfsStreamWrapper::stream_open的调用失败,因此无法打开流。这是我的代码:$this->root = vfsStream::setup('root'); $this->root->addChi…

获取PHP中函数调用者的__FILE__常量 - php

我知道PHP中的__FILE__魔术常数将变成当前执行文件的完整路径和文件名。但是,有什么方法可以使函数的调用文件获得相同的信息吗?例如://foo.php: include "bar.php"; call_it(); //bar.php function call_it() { echo "Calling file: …

如何在PHP中设置get_file_contents的时间限制? - php

有时get_file_contents花费的时间太长,这会挂起整个脚本。有什么方法可以设置get_file_contents的超时限制,而无需修改脚本的最大执行时间?编辑:由于该文件不存在,因此花费了很长时间。我收到“无法打开流:HTTP请求失败!”错误。但这需要永远。 参考方案 通过使用timeout option创建上下文,似乎在PHP> 5.2.…

jQuery File Upload插件-空文件上传结果 - php

在过去的几天里,我一直在使用this插件进行自定义,并将其设置为可以完全按照我的站点要求工作。我在本地服务器上一切正常,没有错误/错误。但是,当我尝试将其上传到我的Plesk服务器时,没有文件显示在加载状态(即使目标文件夹中有图像),并且当我尝试上传im时,出现“空文件上传结果”错误。奇怪的是,即使显示了错误,文件上传似乎仍然起作用,并且相关的图像出现在文件…