呼叫 file_get_contents('https://...') 時常見錯誤:
PHP Warning: file_get_contents(): Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?
原因:PHP 未啟用 OpenSSL 擴充,導致 HTTPS 封裝協議不可用。
<?php
$w = stream_get_wrappers();
echo 'openssl: ', extension_loaded('openssl') ? 'yes' : 'no', "\n";
echo 'http wrapper: ', in_array('http', $w) ? 'yes' : 'no', "\n";
echo 'https wrapper: ', in_array('https', $w) ? 'yes' : 'no', "\n";
echo 'wrappers: ', var_export($w, true), "\n";
輸出若顯示 https wrapper: no 即為 OpenSSL 未啟用。
php.ini,找到 ;extension=openssl,移除分號。libeay32.dll、ssleay32.dll 在系統 PATH 中。https wrapper: yes。cURL 為專門的傳輸庫,支援 HTTPS、POST、Header、Cookie、Proxy、憑證驗證等豐富選項。
<?php
function getHttpsContent($url, array $options = []) {
$ch = curl_init();
$defaults = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true, // 支援 301/302 重導向
CURLOPT_SSL_VERIFYPEER => false, // 生產環境建議 true 並配合 CA 憑證
CURLOPT_SSL_VERIFYHOST => 2, // 驗證 CN 是否匹配域名
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
CURLOPT_TIMEOUT => 30, // 秒
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_HEADER => false,
];
curl_setopt_array($ch, $defaults + $options);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($errno) {
throw new \RuntimeException("cURL error ($errno): $error", $errno);
}
// 可選:檢查 HTTP 狀態碼
if ($info['http_code'] >= 400) {
throw new \RuntimeException("HTTP {$info['http_code']}: $url");
}
return $response;
}
// 使用範例
try {
$html = getHttpsContent('https://api.github.com/users/octocat');
$data = json_decode($html, true);
print_r($data);
} catch (\Throwable $e) {
echo "抓取失敗: " . $e->getMessage();
}
<?php
function postJson($url, array $payload, array $headers = []) {
$ch = curl_init();
$defaultHeaders = [
'Content-Type: application/json',
'Accept: application/json',
];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
CURLOPT_HTTPHEADER => array_merge($defaultHeaders, $headers),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true, // 生產環境務必 true
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_TIMEOUT => 30,
]);
$resp = curl_exec($ch);
if (curl_errno($ch)) throw new \RuntimeException(curl_error($ch), curl_errno($ch));
curl_close($ch);
return json_decode($resp, true);
}
| 錯誤現象 | 可能原因 | 解決方案 |
|---|---|---|
| cURL error 60: SSL certificate problem | CA 憑證缺失或過期 | 下載 cacert.pem,設定 curl.cainfo 或 CURLOPT_CAINFO |
| cURL error 28: Operation timed out | 連線/讀取逾時 | 調大 CURLOPT_TIMEOUT、CURLOPT_CONNECTTIMEOUT;檢查防火牆/Proxy |
| cURL error 35: SSL connect error | TLS 版本不支援(如僅支援 TLS 1.0) | 設定 CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2 |
| 回傳空白/亂碼 | 編碼問題或 GZIP 壓縮 | 加 CURLOPT_ENCODING => 'gzip';確認 mb_detect_encoding |
| 重導向失效 | 未開啟 FOLLOWLOCATION 或 open_basedir 限制 | 確認 CURLOPT_FOLLOWLOCATION => true;或手動處理 301/302 |
抓取 HTTPS 內容,**cURL 是事實標準**。封裝通用函式、統一錯誤處理、配置 CA 憑證、區分開發/生產環境驗證策略,能讓你的 HTTP 客戶端健壯且可維護。