file_get_contents处理错误的好方法 [英] file_get_contents good way to handle errors

查看:388
本文介绍了file_get_contents处理错误的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图错误地处理file_get_contents方法,所以即使用户输入了不正确的网站,它也会回显错误信息,而不是非专业人员。

I am trying to error handle the file_get_contents method so even if the user enters an incorrect website it will echo an error message rather then the unprofessional


警告:file_get_contents(sidiowdiowjdiso):未能打开流:
在第6行没有C:\xampp\htdocs\test.php中的这样的文件或目录

Warning: file_get_contents(sidiowdiowjdiso): failed to open stream: No such file or directory in C:\xampp\htdocs\test.php on line 6

我想如果我试一试,赶上它将能够捕获错误,但没有奏效。

I thought if i make a try and catch it will be able to catch the error but that did not work.

try  
{  
$json = file_get_contents("sidiowdiowjdiso", true); //getting the file content
}  
catch (Exception $e)  
{  
 throw new Exception( 'Something really gone wrong', 0, $e);  
}  


推荐答案

curl_error 而不是file_get_contents:

Try cURL with curl_error instead of file_get_contents:

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>

这篇关于file_get_contents处理错误的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆