萬盛學電腦網

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

PHP cURL 實現 HTTP/HTTPS 請求完整範例:GET、POST、JSON、憑證驗證、超時控制

cURL 是 PHP 最強大的 HTTP 客戶端。本文提供生產級封裝類,涵蓋 GET/POST/JSON、HTTPS 憑證處理、超時重試、錯誤資訊、並發請求。

基礎封裝類

<?php
class HttpClient
{
    private array $defaultOptions = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_CONNECTTIMEOUT => 5,      // 連線超時秒
        CURLOPT_TIMEOUT        => 30,     // 總超時秒
        CURLOPT_SSL_VERIFYPEER => true,   // 生產必須驗證
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT      => 'MyApp/1.0 (+https://example.com)',
        CURLOPT_ENCODING       => 'gzip,deflate', // 自動解壓
    ];

    public function request(string $method, string $url, array $options = []): array
    {
        $ch = curl_init($url);
        $opts = $this->defaultOptions + $options;
        $opts[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
        curl_setopt_array($ch, $opts);

        $body = curl_exec($ch);
        $errNo = curl_errno($ch);
        $errMsg = curl_error($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        if ($errNo) {
            throw new RuntimeException("cURL error {$errNo}: {$errMsg}", $errNo);
        }

        return [
            'status'  => $info['http_code'],
            'headers' => $this->parseHeaders($info['header_size'] ? substr($body, 0, $info['header_size']) : ''),
            'body'    => $info['header_size'] ? substr($body, $info['header_size']) : $body,
            'info'    => $info,
        ];
    }

    public function get(string $url, array $opts = []): array { return $this->request('GET', $url, $opts); }
    public function post(string $url, array $data = [], array $opts = []): array {
        return $this->request('POST', $url, $opts + [
            CURLOPT_POSTFIELDS => is_array($data) ? http_build_query($data) : $data,
        ]);
    }
    public function postJson(string $url, array $data, array $opts = []): array {
        return $this->request('POST', $url, $opts + [
            CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
        ]);
    }

    private function parseHeaders(string $raw): array
    {
        $headers = [];
        foreach (explode("\r\n", $raw) as $line) {
            if (strpos($line, ':') !== false) {
                [$k, $v] = explode(':', $line, 2);
                $headers[trim($k)] = trim($v);
            }
        }
        return $headers;
    }
}
?>

使用範例

<?php
$http = new HttpClient();

// 1. 簡單 GET
$res = $http->get('https://api.example.com/users/1');
echo $res['body'];

// 2. POST Form
$res = $http->post('https://api.example.com/login', ['username'=>'a', 'pwd'=>'b']);

// 3. POST JSON
$res = $http->postJson('https://api.example.com/orders', ['items'=>[['id'=>1,'qty'=>2]]]);

// 4. HTTPS 忽略憑證驗證(僅測試/內網)
$res = $http->get('https://self-signed.badssl.com/', [
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
]);

// 5. 攜帶 Token
$res = $http->get('https://api.example.com/me', [
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token],
]);
?>

進階:並發請求(cURL Multi)

<?php
function multiRequest(array $urls, int $maxConcurrent = 10): array
{
    $mh = curl_multi_init();
    $handles = [];
    $results = [];

    foreach ($urls as $i => $url) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        curl_multi_add_handle($mh, $ch);
        $handles[$i] = $ch;
    }

    $running = null;
    do {
        curl_multi_exec($mh, $running);
        curl_multi_select($mh, 0.1);
    } while ($running > 0);

    foreach ($handles as $i => $ch) {
        $results[$i] = [
            'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
            'body'   => curl_multi_getcontent($ch),
            'error'  => curl_error($ch),
        ];
        curl_multi_remove_handle($mh, $ch);
        curl_close($ch);
    }
    curl_multi_close($mh);
    return $results;
}
?>

常見問題速查

現象原因解決
HTTPS 返回 0 / SSL connect error憑證不信任、CA 缺失、TLS 版本過低更新 ca-certificates、指定 `CURLOPT_CAINFO`、或測試環境關閉驗證
POST 資料對方收不到Content-Type 不對、資料格式錯JSON 需設 `Content-Type: application/json`,Form 用 `http_build_query`
中文亂碼編碼不一致確保 PHP 腳本 UTF-8、資料庫 UTF-8、API 回傳 UTF-8,`json_encode(..., JSON_UNESCAPED_UNICODE)`
大檔案下載記憶體爆炸`CURLOPT_RETURNTRANSFER` 將整個回應載入記憶體用 `CURLOPT_WRITEFUNCTION` 回調流式寫入檔案

現代替代:Guzzle / Symfony HttpClient

新專案建議直接用 composer require guzzlehttp/guzzle 或 symfony/http-client,提供 PSR-18/PSR-17 標準、中介軟體、重試、熔斷、非同步、測試雙工等企業級能力,避免重複造輪子。

copyright © 萬盛學電腦網 all rights reserved