2013-04-21 113 views
6

我尝试错误,以便即使用户输入不正确的网站它会回应一个错误消息,而那么不专业的file_get_contents处理错误的好方法

警告处理的file_get_contents方法:的file_get_contents(sidiowdiowjdiso):未能打开流: C中没有这样的文件或目录:\ XAMPP \ htdocs中\上线test.php的6

我想,如果我做一个尝试,抓住它就能捕获错误但不工作。

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

如果你想最起码读的URL,你应该确认他们看起来像URL第一,否则人们可以在服务器上读取文件。一个更好的选择可能是使用curl – 2013-04-21 12:05:32

回答

10

尝试卷曲与curl_error代替的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); 
?> 
+8

向下投票,因为这不是关于使用的file_get_contents的答案OP的问题() - 提供了一个替代方案是不是一个真正的解决方案。 OP询问如何处理来自file_get_contents()的错误和警告,而不是如何以完全不同的方式进行操作。请注意,卷曲不是直接替代了PHP的file_get_contents()函数和任何人做,此举将有可能严重重构自己的代码,因此为什么这不是一个可以接受的答案。 – tpartee 2016-12-20 00:48:19

7

file_get_contents不扔在错误的异常,而不是返回false,这样你就可以检查返回值是假的:

$json = file_get_contents("sidiowdiowjdiso", true); 
if ($json === false) { 
    //There is an error opening the file 
} 

这样你仍然得到警告,如果你想要删除它,你需要把@file_get_contents面前。 (这被认为是不好的做法)

$json = @file_get_contents("sidiowdiowjdiso", true); 
+7

这可能是更好的讨论[使用error_reporting()](http://uk1.php.net/manual/en/function.error-reporting.php),比推广使用'@'的 – 2013-04-21 12:02:33

+0

也许值得注意的是,在使用'@'前缀可以防止显示错误信息给用户,如果你正在登录错误使用分配给'set_error_handler'的功能,那么你仍然会看到记录在文件中的警告文件,如果你还没有,那么它们将被包含在你的Web服务器日志中。 – richhallstoke 2016-11-29 10:54:05

4

你可以做任何操作:

设置一个全局错误处理程序(将处理警告以及所有未处理的例外情况):http://php.net/manual/en/function.set-error-handler.php

或者通过检查file_get_conten的返回值ts函数(使用===运算符,因为它会在失败时返回布尔值false),然后相应地管理错误消息,并通过预先添加“@”来禁用错误报告:

$json = @file_get_contents("file", true); 
if($json === false) { 
// error handling 
} else { 
// do something with $json 
} 
+0

当我试图验证码总是读即使URL是有效的假 – Hashey100 2013-04-21 12:20:08

-1

作为解决您的问题,请尝试执行下面的代码片段

try 
{ 
    $json = @file_get_contents("sidiowdiowjdiso", true); //getting the file content 
    if($json==false) 
    { 
    throw new Exception('Something really gone wrong'); 
    } 
} 
catch (Exception $e) 
{ 
    echo $e->getMessage(); 
} 
+0

仍然得到一个警告,当我执行的代码 – Hashey100 2013-04-21 12:19:48

+0

现在,请尝试执行上面的代码片断 – 2013-04-21 12:23:17

+0

相同的结果总是返回false即使进入这样一个有效的URL如www.google.com – Hashey100 2013-04-21 12:25:15