萬盛學電腦網

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

PHP cURL 封裝類完整實作指南

環境準備:啟用 cURL 擴展

  1. 編輯 php.ini,移除 ;extension=php_curl.dll 前的分號。
  2. 將 libeay32.dll、ssleay32.dll、php5ts.dll 複製至系統目錄(如 C:\Windows)。
  3. 重啟 Apache/Nginx。
  4. 用 phpinfo() 確認 cURL 區塊出現。

封裝類設計目標

  • 統一錯誤處理與例外捕獲
  • 支援 Cookie 持久化(模擬登入)
  • 提供 Unicode 轉 UTF-8 工具方法
  • 靈活的選項陣列傳遞

核心類別代碼

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

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

    /** 發送請求並返回回應字串 */
    public function getResponseText(array $curlOptions) {
        // 強制返回字串
        $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) {
            $responseText = false;
        } finally {
            curl_close($curl);
        }
        return $responseText;
    }

    /** Unicode \uXXXX 轉 UTF-8 */
    public function unicodeToUtf8($string) {
        $string = str_replace('u', '', strtolower($string));
        $len = strlen($string) / 4;
        $result = '';
        for ($i = 0; $i < $len; $i++) {
            $hex = substr($string, $i * 4, 4);
            $code = hexdec($hex);
            if ($code < 128) {
                $result .= chr($code);
            } elseif ($code < 2048) {
                $result .= chr(192 + (($code - 64) / 64)) . chr(128 + ($code % 64));
            } else {
                $result .= chr(224 + (($code - 4096) / 4096))
                         . chr(128 + ((($code % 4096) - 64) / 64))
                         . chr(128 + ($code % 64));
            }
        }
        return $result;
    }

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

實際呼叫範例

require_once 'curl.class.php';

$curl = new Curl();
$options = [
    CURLOPT_URL            => 'https://www.example.com/api',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_REFERER        => 'https://www.example.com',
    CURLOPT_HTTPHEADER     => [
        'X-FORWARDED-FOR: 139.197.14.19',
        'CLIENT-IP: 127.0.0.1'
    ],
    CURLOPT_HEADER         => 1,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => 'ids=897&Submit=%E6%8A%95%E7%A5%A8',
    CURLOPT_TIMEOUT        => $curl->timeout,
];

$response = $curl->getResponseText($options);
var_dump($response);

第二種風格:靜態工廠模式

另一種常見封裝採用靜態 create() 建立 cURL handle,再鏈式設定選項:

class Curl {
    static function create() { return curl_init(); }

    function execute($method, $url, $fields = '', $userAgent = '', $headers = '', $user = '', $pass = '') {
        $ch = self::create();
        if (!$ch || !$url) return false;

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

        if ($user) curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");

        $method = strtolower($method);
        if ($method === 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            if (is_array($fields)) {
                $fields = http_build_query($fields);
            }
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        } elseif ($method === 'put') {
            curl_setopt($ch, CURLOPT_PUT, true);
        }

        if ($userAgent) curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
        if (is_array($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        return curl_exec($ch);
    }
}

最佳實踐提醒

  • 生產環境務必驗證 SSL 憑證(CURLOPT_SSL_VERIFYPEER => true)。
  • 設定合理的 CURLOPT_TIMEOUT 與 CURLOPT_CONNECTTIMEOUT 避免阻塞。
  • 重複請求同一域名時,重用 Cookie 檔案可保持會話。
  • 針對 API 整合,建議再封裝一層 Service 類別,統一處理簽名、重試、日誌。
copyright © 萬盛學電腦網 all rights reserved