PHP函數file_get_contents()使用 https 協議時報錯:SSL operation failed


場景:

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"));
?>

引用:https://stackoverflow.com/questions/14078182/openssl-file-get-contents-failed-to-enable-crypto

 

方法三:

使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()函數。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM