PHP 預設未啟用 OpenSSL 時,file_get_contents('https://...') 會拋出 Unable to find the wrapper "https" 警告。本文提供三種解決方案:啟用 php_openssl、cURL 封裝函式、stream_context 參數控制,並對比優劣與生產環境建議。
php.ini,取消註解 extension=openssl(PHP 7.2+ 為 extension=php_openssl.dll)。libeay32.dll、ssleay32.dll(PHP 7.1 前)或 libcrypto-*.dll/libssl-*.dll(PHP 7.2+)在 PATH 中(通常在 PHP 目錄)。# Ubuntu/Debian
sudo apt-get install php-openssl # 或 php8.2-openssl
sudo systemctl restart php8.2-fpm # 或 apache2/nginx
驗證:php -m | grep openssl 輸出 openssl 即成功。
<?php
/**
* 通用 HTTP 請求(支援 HTTP/HTTPS、重導向、標頭、逾時、憑證驗證)
*/
function httpRequest(string $url, array $options = []): string|false
{
if (!function_exists('curl_init')) {
throw new RuntimeException('cURL extension not installed');
}
$defaults = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true, // 生產環境必須 true
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_USERAGENT => 'PHP-HTTP-Client/1.0',
CURLOPT_HEADER => false, // true 時回傳含標頭
];
$ch = curl_init();
curl_setopt_array($ch, $defaults + $options);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$err = curl_error($ch);
curl_close($ch);
error_log("cURL error [$url]: $err");
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
error_log("HTTP $httpCode [$url]");
return false;
}
return $response;
}
// 使用
$html = httpRequest('https://api.example.com/data');
$json = httpRequest('https://api.example.com/data', [
CURLOPT_HTTPHEADER => ['Accept: application/json', 'Authorization: Bearer xxx'],
]);
<?php
$ctx = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "User-Agent: PHP\r\nAccept: application/json\r\n",
'timeout' => 10,
'ignore_errors' => true, // 取得 4xx/5xx 內容而非拋警告
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'cafile' => '/etc/ssl/certs/ca-certificates.crt', // Linux 憑證包
// 'verify_peer' => false, // 僅開發環境臨時關閉
],
]);
$json = file_get_contents('https://api.example.com/data', false, $ctx);
if ($json === false) {
// 錯誤處理
}
$data = json_decode($json, true);
| 方案 | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|
| 啟用 openssl | 原生函式無縫支援、無額外代碼 | 需修改 php.ini、重啟服務、共享主機可能無權限 | 自控伺服器、長期專案 |
| cURL 封裝 | 功能最全(POST、檔案上傳、Cookie、代理、HTTP/2、證書釘選) | 需編寫封裝、依賴 cURL 擴充 | 生產環境標準選擇、API 客戶端 |
| stream_context | 零依賴、語法簡潔、支援 HTTPS | 功能有限(無自動重導向、無並發、無進度回調) | 簡單 GET、臨時腳本、無 cURL 環境 |
| 錯誤 | 原因 | 修正 |
|---|---|---|
| SSL certificate problem: self signed certificate | 自簽憑證/內網測試環境 | 開發環境 verify_peer=false;生產必須部署有效 CA 憑證 |
| SSL: certificate subject name does not match | 域名不匹配(IP 訪問、CDN 回源) | 修正 DNS/憑證 SAN,或 verify_peer_name=false(不推薦) |
| cURL error 60: SSL certificate problem | 缺少 CA 憑證包 | Linux 安裝 ca-certificates;Windows 設定 curl.cainfo 指向 cacert.pem |