PHP升級到7以後直接用file_get_contents和get_headers讀取https開頭的URL會報錯:
Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed Warning: get_headers(): Failed to enable crypto Warning: get_headers(): failed to open stream: operation failed
可以用stream_context_create設置不驗證的選項,下面是我寫的幾個函數:
/**
* 函數:讀取使用SSL證書的網址
* 輸入:$url網址
* 輸出:讀取網址獲得的内容
*/
function file_get_contents_ssl($url) {
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$contents = file_get_contents($url, false, stream_context_create($stream_opts));
return $contents;
}
/**
* 函數:讀取使用SSL證書的網址headers
* 輸入:$url網址
* 輸出:讀取網址獲得的數組
*/
function get_headers_ssl($url) {
$stream_opts = [
'ssl' => [
'verify_host' => false,
'verify_peer' => false,
'verify_peer_name' => false,
],
];
$headers = get_headers($url, 1, stream_context_create($stream_opts));
return $headers;
}
/**
* 函數:網址頁面是否存在
* 輸入:$url網址
* 返回:是或者否
*/
function url_exists($url) {
$array = get_headers_ssl($url);
if ($array == FALSE) return FALSE;
if (strpos(json_encode($array),' 200 OK') != FALSE) {
return TRUE;
} else {
return FALSE;
}
}
這幾個函數就可以在其它地方被調用了。
评论2
沒看懂,高手就是高www.benedetti
沒看懂,高手就是高,能 在詳細具體點嗎?真有疑問可以留言,但帶網址來做宣傳就沒有必要留言了,謝謝。
真有疑問可以留言,但帶網址來做宣傳就沒有必要留言了,謝謝。