場景:
file_get_contents() 函數(shù)是用于將文件的內(nèi)容讀入到一個字符串中,是讀取文件內(nèi)容常用的函數(shù)之一。
但是有時在服務(wù)器上使用file_get_contents() 函數(shù)請求https 協(xié)議的url文件時會報錯誤,無法正確讀取文件內(nèi)容,
查看log日志,日志內(nèi)容類似如下:
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 ......
原因:
服務(wù)器未正確配置好https證書
解決方法:(三種解決方法)
方法一:
下載https證書到服務(wù)器
服務(wù)器 下載這個證書,http://curl.haxx.se/ca/cacert.pem
php.ini 配置
openssl.cafile = "/etc/ssl/certs/cacert.pem"http://你實際下載證書的路徑
重啟 php 即可
方法二:
使用cURL 函數(shù)處理 https 的參數(shù),獲取文件內(nèi)容
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")); ?>
引用:https://stackoverflow.com/questions/14078182/openssl-file-get-contents-failed-to-enable-crypto
方法三:
使file_get_contents()函數(shù)跳過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));
開發(fā)中建議使用cURL 函數(shù)替代file_get_contents()函數(shù)。