萬盛學電腦網

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

PHP cURL 封裝類完整實作與進階用法

cURL 擴展安裝與配置

在 Windows 環境下啟用 cURL 需完成三步驟:

  1. 編輯 php.ini,移除 ;extension=php_curl.dll 前的分號(可透過 phpinfo() 確認配置檔路徑)。
  2. 將 libeay32.dll、ssleay32.dll、php5ts.dll、php_curl.dll 複製至系統目錄(通常為 C:\Windows\System32 或 Apache 的 bin 目錄)。
  3. 重啟 Apache 服務使配置生效。

基礎封裝類實作

以下 Curl 類封裝常用請求參數、Cookie 管理、錯誤處理與 Unicode 轉換工具方法:

<?php
class Curl
{
    public $cookieFile;
    public $timeout = 160;

    public function __construct($dir = '')
    {
        $this->cookieFile = $this->getTemporaryCookieFileName($dir);
    }

    /**
     * 發送請求並獲取回應內容
     * @param array $curlOptions curl_setopt_array 參數陣列
     * @return string|false 成功回傳字串,失敗回傳 false
     */
    public function getResponseText(array $curlOptions)
    {
        // 強制啟用字串回傳模式
        if (!isset($curlOptions[CURLOPT_RETURNTRANSFER]) || !$curlOptions[CURLOPT_RETURNTRANSFER]) {
            $curlOptions[CURLOPT_RETURNTRANSFER] = true;
        }

        $curl = curl_init();
        curl_setopt_array($curl, $curlOptions);

        $responseText = '';
        try {
            $responseText = curl_exec($curl);
            if (($errno = curl_errno($curl)) !== CURLE_OK) {
                throw new Exception(curl_error($curl), $errno);
            }
        } catch (Exception $e) {
            // 可在此接入日誌記錄:error_log($e->getMessage());
            $responseText = false;
        }

        curl_close($curl);
        return $responseText;
    }

    /**
     * Unicode 轉 UTF-8 工具方法
     * @param string $string 形如 \u0041 的 Unicode 字串
     * @return string UTF-8 編碼字串
     */
    public function unicodeToUtf8($string)
    {
        $string = str_replace('u', '', strtolower($string));
        $length = strlen($string) / 4;
        $result = '';

        for ($i = 0; $i < $length; $i++) {
            $hex = substr($string, $i * 4, 4);
            $code = hexdec($hex);
            $utf8 = '';

            if ($code < 128) {
                $utf8 = chr($code);
            } elseif ($code < 2048) {
                $utf8 .= chr(192 + (($code - ($code % 64)) / 64));
                $utf8 .= chr(128 + ($code % 64));
            } else {
                $utf8 .= chr(224 + (($code - ($code % 4096)) / 4096));
                $utf8 .= chr(128 + ((($code % 4096) - ($code % 64)) / 64));
                $utf8 .= chr(128 + ($code % 64));
            }
            $result .= $utf8;
        }
        return $result;
    }

    private function getTemporaryCookieFileName($dir = '.')
    {
        return str_replace('\\', '/', tempnam($dir, 'tmp'));
    }
}

使用範例:模擬瀏覽器 POST 請求

<?php
include_once 'curl.class.php';

$client = new Curl();

$options = [
    CURLOPT_URL            => 'https://example.com/addTicket.jsp',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_REFERER        => 'https://example.com/zw2',
    CURLOPT_HTTPHEADER     => [
        'X-FORWARDED-FOR: 139.197.14.19',
        'CLIENT-IP: 127.0.0.1',
        'Proxy-Client-IP: 139.197.14.19',
        'WL-Proxy-Client-IP: 139.197.14.19',
    ],
    CURLOPT_HEADER         => 1,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => 'ids=897&Submit=%E6%8A%95%E7%A5%A8',
    CURLOPT_TIMEOUT        => $client->timeout,
];

echo $client->getResponseText($options);

替代實作:靜態工廠模式封裝

另一種常見封裝採用靜態 create() 方法回傳 cURL 資源,配合 execute() 統一參數設定:

<?php
class Curl
{
    public static function create()
    {
        $ch = curl_init();
        if ($ch === false) {
            return false;
        }
        // 通用預設選項
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        return $ch;
    }

    public function execute($method, $url, $fields = '', $userAgent = '', $headers = '', $username = '', $password = '')
    {
        $ch = self::create();
        if ($ch === false || !is_string($url) || !$url) {
            return false;
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);

        if (strtoupper($method) === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        }

        if ($userAgent) {
            curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
        }
        if ($headers) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, (array)$headers);
        }
        if ($username && $password) {
            curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
        }

        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}

進階技巧與注意事項

  • SSL 憑證驗證:生產環境建議啟用 CURLOPT_SSL_VERIFYPEER = true 並配置 CURLOPT_CAINFO 指向有效 CA 憑證束,僅在測試環境關閉驗證。
  • Cookie 持久化:利用 CURLOPT_COOKIEJAR 與 CURLOPT_COOKIEFILE 實現跨請求會話保持。
  • 多執行緒併發:大量並發請求時可使用 curl_multi_* 族函數或 RollingCurl 等第三方庫提升吞吐量。
  • 錯誤處理規範:統一捕獲 curl_errno() 非零狀態,記錄 curl_error() 訊息並拋出自訂異常,便於上層統一處理。

封裝類的核心價值在於將重複的初始化、選項設定、錯誤處理、資源釋放流程標準化,減少業務代碼中的樣板代碼,同時提供擴展點支援特殊場景(如代理、憑證、進度回調等)。

copyright © 萬盛學電腦網 all rights reserved