2013-04-21 33 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