2015-03-02 103 views
4
file_get_contents('https://invalid-certificate.com'); 

產生以下PHP警告和錯誤:如何獲取file_get_contents()警告而不是PHP錯誤?

PHP warning: Peer certificate CN='*.invalid-certificate.net' did not match expected CN='invalid-certificate.com'

PHP error: file_get_contents(https://invalid-certificate.com): failed to open stream: operation failed


我想用異常而不是PHP的警告,所以:

$response = @file_get_contents('https://invalid-certificate.com'); 

if ($response === false) { 
    $error = error_get_last(); 
    throw new \Exception($error['message']); 
} 

但現在的異常消息是:

file_get_contents(https://invalid-certificate.com): failed to open stream: operation failed

這是正常的,error_get_last()回報的最後一個錯誤 ...

我怎樣才能得到警告,其中包含有關失敗的許多有價值的信息?

+0

捲曲最好是處理錯誤而不是'file_g et_contents()' – 2015-03-02 04:56:50

+0

@jogesh_pi是的我知道,我想知道'file_get_contents()'。 – 2015-03-02 05:02:21

回答

1

您可以好好利用set_error_handler和轉換這些錯誤爲異常和使用異常正確

<?php 
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) { 
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 
}); 

try { 
    $response = file_get_contents('https://invalid-certificate.com'); 
} catch (ErrorException $e) { 
    var_dump($e); // ofcourse you can just grab the desired info here 
} 
?> 

一個更簡單的版本將是

<?php 
set_error_handler(function($errno, $errstr) { 
    var_dump($errstr); 
}); 
$response = file_get_contents('https://invalid-certificate.com'); 
?> 

Fiddle

+0

這確實是一個「帶出大槍」的解決方案,我寧願使用更簡單的替代方案(如果存在的話) – 2015-03-02 05:02:00

+0

@MatthieuNapoli我認爲你應該「帶出大槍」,因爲在腳本級別,你只能得到最後一個錯誤,沒有這種錯誤處理程序。 – bansi 2015-03-02 05:06:55

+0

在編輯中查看更簡單的版本 – 2015-03-02 05:07:42

相關問題