萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 抓取 HTTPS 內容完整解決方案:file_get_contents 與 cURL 實戰

問題背景

呼叫 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 未啟用。

方案一:啟用 OpenSSL(需服務器權限)

  1. 編輯 php.ini,找到 ;extension=openssl,移除分號。
  2. Windows 還需確認 libeay32.dll、ssleay32.dll 在系統 PATH 中。
  3. 重啟 Web 服務(Apache/Nginx + PHP-FPM)。
  4. 再次執行診斷腳本確認 https wrapper: yes。

方案二:使用 cURL(推薦、無需改 php.ini、功能更強)

cURL 為專門的傳輸庫,支援 HTTPS、POST、Header、Cookie、Proxy、憑證驗證等豐富選項。

通用 HTTPS GET 封裝函式

<?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();
}

進階:POST JSON 資料並攜帶 Header

<?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 problemCA 憑證缺失或過期下載 cacert.pem,設定 curl.cainfo 或 CURLOPT_CAINFO
cURL error 28: Operation timed out連線/讀取逾時調大 CURLOPT_TIMEOUT、CURLOPT_CONNECTTIMEOUT;檢查防火牆/Proxy
cURL error 35: SSL connect errorTLS 版本不支援(如僅支援 TLS 1.0)設定 CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2
回傳空白/亂碼編碼問題或 GZIP 壓縮加 CURLOPT_ENCODING => 'gzip';確認 mb_detect_encoding
重導向失效未開啟 FOLLOWLOCATION 或 open_basedir 限制確認 CURLOPT_FOLLOWLOCATION => true;或手動處理 301/302

file_get_contents vs cURL 選擇指南

  • file_get_contents:簡單 GET、允許修改 php.ini、不需複雜 Header/Cookie/Proxy → 可用。
  • cURL:需 POST/PUT/DELETE、自訂 Header、Cookie 管理、Proxy、憑證控制、效能要求高、無法修改 php.ini(共享主機)→ **首選**。

總結

抓取 HTTPS 內容,**cURL 是事實標準**。封裝通用函式、統一錯誤處理、配置 CA 憑證、區分開發/生產環境驗證策略,能讓你的 HTTP 客戶端健壯且可維護。

copyright © 萬盛學電腦網 all rights reserved