萬盛學電腦網

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

PHP cURL 完整指南:從基礎 GET/POST 到代理、模擬登入、並發請求實戰

cURL 是 PHP 網路請求的瑞士刀

PHP 的 cURL 擴展(libcurl 綁定)支援 HTTP/HTTPS、FTP、SMTP、IMAP、MQTT 等十幾種協定,提供精細的連線控制:超時、重試、代理、憑證驗證、Cookie 管理、多工並發。掌握 cURL 是 PHP 後端串接第三方 API、爬蟲、微服務通訊的必備技能。

核心函數速查

函數用途
curl_init()初始化會話,回傳 handle
curl_setopt()設定單一選項
curl_setopt_array()批次設定選項(陣列)
curl_exec()執行請求,回傳回應主體
curl_getinfo()取得傳輸資訊(HTTP 代碼、耗時、大小等)
curl_error() / curl_errno()錯誤訊息/代碼
curl_close()關閉會話釋放資源
curl_multi_* 系列並發多請求處理

基礎範例:GET 請求與錯誤處理

<?php
function httpGet(string $url, array $options = []): array
{
    $ch = curl_init($url);
    
    $defaults = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MyApp/1.0)',
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_ENCODING => 'gzip,deflate',
        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);
    
    return [
        'success' => $errno === 0,
        'http_code' => $info['http_code'] ?? 0,
        'body' => $response,
        'error' => $error,
        'errno' => $errno,
        'info' => $info,
    ];
}

// 使用
$result = httpGet('https://api.example.com/users/123');
if ($result['success']) {
    $data = json_decode($result['body'], true);
} else {
    error_log("cURL 錯誤 [{$result['errno']}]: {$result['error']}");
}
?>

POST 請求:表單、JSON、檔案上傳

<?php
function httpPost(string $url, mixed $data, array $options = []): array
{
    $ch = curl_init($url);
    
    $isJson = is_array($data) || is_object($data);
    $postFields = $isJson ? json_encode($data, JSON_UNESCAPED_UNICODE) : http_build_query($data);
    
    $defaults = [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $isJson 
            ? ['Content-Type: application/json', 'Accept: application/json']
            : ['Content-Type: application/x-www-form-urlencoded'],
    ];
    
    curl_setopt_array($ch, $defaults + $options);
    
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    return [
        'success' => $errno === 0,
        'http_code' => $info['http_code'] ?? 0,
        'body' => $response,
        'error' => curl_error($ch),
    ];
}

// 檔案上傳(multipart/form-data)
function httpPostFile(string $url, string $filePath, string $fieldName = 'file', array $extraFields = []): array
{
    $ch = curl_init($url);
    $cfile = new CURLFile($filePath, mime_content_type($filePath), basename($filePath));
    $postFields = array_merge($extraFields, [$fieldName => $cfile]);
    
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SAFE_UPLOAD => true, // PHP 5.6+ 預設開啟
    ]);
    
    return [
        'success' => curl_errno($ch) === 0,
        'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
        'body' => curl_exec($ch),
        'error' => curl_error($ch),
    ];
}
?>

代理與通道設定

<?php
// HTTP/HTTPS 代理
curl_setopt($ch, CURLOPT_PROXY, 'https://proxy.example.com:3128');
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'username:password'); // 若需認證
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true); // HTTP CONNECT 隧道(HTTPS 目標需開啟)

// SOCKS5 代理
curl_setopt($ch, CURLOPT_PROXY, 'socks5://127.0.0.1:1080');
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);

// 忽略 SSL 驗證(僅測試環境!生產嚴禁)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER => false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST => false);

// 自定義 CA 憑證(生產環境自簽憑證)
curl_setopt($ch, CURLOPT_CAINFO, '/path/to/ca-bundle.crt');
?>

模擬登入:Cookie 管理與 CSRF Token 處理

<?php
class SessionCrawler
{
    private $ch;
    private string $cookieFile;
    
    public function __construct(string $cookieFile = '')
    {
        $this->ch = curl_init();
        $this->cookieFile = $cookieFile ?: sys_get_temp_dir() . '/curl_cookie_' . uniqid() . '.txt';
        
        curl_setopt_array($this->ch, [
            CURLOPT_COOKIEJAR => $this->cookieFile,
            CURLOPT_COOKIEFILE => $this->cookieFile,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        ]);
    }
    
    public function get(string $url): string
    {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);
        return curl_exec($this->ch) ?: '';
    }
    
    public function post(string $url, array $data): string
    {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_POST, true);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($data));
        return curl_exec($this->ch) ?: '';
    }
    
    // 從 HTML 提取 CSRF Token
    public function extractCsrfToken(string $html, string $selector = 'input[name="_token"]'): ?string
    {
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        $node = $xpath->query($selector)->item(0);
        return $node ? $node->getAttribute('value') : null;
    }
    
    public function __destruct()
    {
        curl_close($this->ch);
        @unlink($this->cookieFile);
    }
}

// 使用範例:Discuz/論壇模擬登入
$crawler = new SessionCrawler();

// 1. 取得登入頁面,解析 formhash
$loginPage = $crawler->get('https://forum.example.com/member.php?mod=logging&action=login');
$formhash = $crawler->extractCsrfToken($loginPage, 'input[name="formhash"]');

// 2. 提交登入表單
$loginResult = $crawler->post('https://forum.example.com/member.php?mod=logging&action=login&loginsubmit=yes', [
    'formhash' => $formhash,
    'username' => 'my_user',
    'password' => 'my_pass',
    'questionid' => 0,
    'answer' => '',
]);

// 3. 攜帶 Cookie 訪問需登入頁面
$profile = $crawler->get('https://forum.example.com/home.php?mod=spacecp');
?>

並發請求:curl_multi 非阻塞批次處理

<?php
function multiRequest(array $urls, int $maxConcurrent = 10, array $commonOptions = []): Generator
{
    $mh = curl_multi_init();
    $handles = [];
    $pending = $urls;
    
    // 初始化第一批
    for ($i = 0; $i < min($maxConcurrent, count($pending)); $i++) {
        $url = array_shift($pending);
        $ch = curl_init($url);
        curl_setopt_array($ch, $commonOptions + [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
        ]);
        curl_multi_add_handle($mh, $ch);
        $handles[(int)$ch] = ['url' => $url, 'ch' => $ch];
    }
    
    $active = null;
    do {
        $mrc = curl_multi_exec($mh, $active);
        
        // 處理完成的請求
        while ($done = curl_multi_info_read($mh)) {
            $ch = $done['handle'];
            $info = $handles[(int)$ch] ?? ['url' => 'unknown'];
            $info['result'] = [
                'success' => $done['result'] === CURLE_OK,
                'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
                'body' => curl_multi_getcontent($ch),
                'error' => curl_error($ch),
                'errno' => curl_errno($ch),
            ];
            yield $info;
            
            curl_multi_remove_handle($mh, $ch);
            curl_close($ch);
            unset($handles[(int)$ch]);
        }
        
        // 補充新請求
        while ($active < $maxConcurrent && $pending) {
            $url = array_shift($pending);
            $ch = curl_init($url);
            curl_setopt_array($ch, $commonOptions + [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
            curl_multi_add_handle($mh, $ch);
            $handles[(int)$ch] = ['url' => $url, 'ch' => $ch];
            $active++;
        }
        
        if ($active) {
            curl_multi_select($mh, 1.0); // 等待活動
        }
    } while ($active);
    
    curl_multi_close($mh);
}

// 使用:並發抓取 100 個 API,每次 10 個並發
foreach (multiRequest($urls, 10) as $result) {
    if ($result['result']['success']) {
        processData($result['url'], json_decode($result['result']['body'], true));
    } else {
        error_log("失敗:{$result['url']} - {$result['result']['error']}");
    }
}
?>

效能調優關鍵參數

參數建議值說明
CURLOPT_TIMEOUT10-30 秒總超時,防止卡死
CURLOPT_CONNECTTIMEOUT3-5 秒連線階段超時
CURLOPT_TCP_KEEPALIVE1保持長連線,減少握手
CURLOPT_TCP_KEEPIDLE120閒置多久發送保活
CURLOPT_FORBID_REUSE0允許連線重用(預設)
CURLOPT_DNS_CACHE_TIMEOUT120DNS 快取秒數
CURLOPT_BUFFERSIZE16384讀寫緩衝區大小

常見錯誤代碼速查

  • CURLE_OPERATION_TIMEDOUT (28):超時,檢查網路/防火牆/超時設定
  • CURLE_SSL_CACERT (60):CA 憑證驗證失敗,補全 CA bundle 或指定 CURLOPT_CAINFO
  • CURLE_COULDNT_RESOLVE_HOST (6):DNS 解析失敗
  • CURLE_RECV_ERROR (56):接收資料失敗,常見於防火牆斷開或伺服器重置
  • CURLE_HTTP2_STREAM (92):HTTP/2 流錯誤,嘗試 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1

總結

cURL 是 PHP 網路層的基石。關鍵掌握:正確的錯誤處理流程、Cookie 持久化會話、multipart 檔案上傳、curl_multi 並發模型、SSL/TLS 安全配置。現代專案亦可考慮 GuzzleHttp(面向物件封裝)、Swoole\Coroutine\Http\Client(協程非阻塞)等上層抽象,但理解底層 cURL 行為對除錯仍不可或缺。

copyright © 萬盛學電腦網 all rights reserved