場景:
file_get_contents() 函數是用於將文件的內容讀入到一個字符串中,是讀取文件內容常用的函數之一。
但是有時在服務器上使用file_get_contents() 函數請求https 協議的url文件時會報錯誤,無法正確讀取文件內容,
查看log日誌,日誌內容類似如下:
PHP Warning: file_get_contents(): Failed to enable crypto in ......
PHP Warning: file_get_contents......: failedream: operation failed in ......
PHP Warning: file_get_contents(): SSL operatwith code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verin ......
原因:
服務器未正確配置好https證書
解決方法一:
下載https證書到服務器
服務器 下載這個證書,http://curl.haxx.se/ca/cacert.pem
php.ini 配置
openssl.cafile = "/etc/ssl/certs/cacert.pem"//你實際下載證書的路徑
重啓 php 即可
解決方法二:
使用cURL 函數處理 https 的參數,獲取文件內容
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://xxx.xxx.xxx"));
?>
解決方法三:
使file_get_contents()函數跳過https驗證
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$response = file_get_contents("https://xxx.xxx.xxx",false, stream_context_create($stream_opts));
開發中建議使用cURL 函數替代file_get_contents()函數。