萬盛學電腦網

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

PHP 呼叫外部 HTTP 介面完整指南:file_get_contents、cURL、Guzzle 最佳實務

PHP 整合第三方 API、微服務溝通、網頁爬蟲都需要發送 HTTP 請求。本文比較三種主流方式:原生 `file_get_contents`、cURL 擴充、Guzzle HTTP Client,涵蓋 GET/POST、JSON、檔案上傳、超時、重試、錯誤處理。

方式比較總覽

特性file_get_contentscURLGuzzle
依賴核心(需 allow_url_fopen)cURL 擴充Composer 套件
HTTP 方法僅 GET(需 stream context 支援 POST)完整支援完整支援
HTTPS/憑證基本支援完整控制完整控制
超時控制stream context精確控制精確控制
錯誤處理回傳 false、觸發 warningcurl_error、curl_errno例外物件、PSR-7/18
並發/非同步不支援curl_multiPromise、非同步
中介軟體/擴充無無豐富生態
推薦場景簡單 GET、快速原型底層控制、特殊協定現代專案、API 整合、生產環境

方法一:file_get_contents + Stream Context

<?php
// 簡單 GET
$url = 'https://api.example.com/users/123';
$json = @file_get_contents($url);
if ($json === false) {
    throw new Exception("Request failed");
}
$data = json_decode($json, true);

// 帶參數 GET
$params = ['q' => 'php', 'limit' => 10];
$url = 'https://api.example.com/search?' . http_build_query($params);
$json = @file_get_contents($url);

// POST JSON(需 stream context)
$postData = json_encode(['name' => 'John', 'email' => 'john@example.com']);
$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\nContent-Length: " . strlen($postData),
        'content' => $postData,
        'timeout' => 10, // 秒
        'ignore_errors' => true, // 取得 4xx/5xx 回應內容
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ],
]);
$response = @file_get_contents('https://api.example.com/users', false, $context);
$status = $http_response_header[0] ?? 'HTTP/1.1 000'; // 解析狀態碼

方法二:cURL 完整控制

<?php
function curlRequest(string $url, array $options = []): array {
    $ch = curl_init();
    
    $defaults = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'MyApp/1.0 (+https://example.com)',
        CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
    ];
    
    // 合併選項
    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 Exception("cURL error ($errno): $error");
    }
    
    return [
        'body' => $response,
        'status' => $info['http_code'],
        'headers' => $info['header_size'] ? substr($response, 0, $info['header_size']) : '',
        'info' => $info,
    ];
}

// GET
$result = curlRequest('https://api.example.com/users/123');

// POST JSON
$result = curlRequest('https://api.example.com/users', [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode(['name' => 'John']),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);

// 檔案上傳(CURLFile PHP 5.5+)
$result = curlRequest('https://api.example.com/upload', [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('/path/to/image.jpg', 'image/jpeg', 'avatar.jpg'),
        'user_id' => '123',
    ],
]);

方法三:Guzzle HTTP Client(現代標準)

<?php
// Composer: require guzzlehttp/guzzle:~7.0
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;

$client = new Client([
    'base_uri' => 'https://api.example.com/',
    'timeout' => 10.0,
    'connect_timeout' => 5.0,
    'headers' => [
        'User-Agent' => 'MyApp/1.0',
        'Accept' => 'application/json',
    ],
    // 中介軟體:重試、日誌、快取
    'handler' => \GuzzleHttp\HandlerStack::create(),
]);

// 同步請求
try {
    $response = $client->get('users/123');
    $data = json_decode($response->getBody()->getContents(), true);
    $status = $response->getStatusCode();
} catch (RequestException $e) {
    if ($e->hasResponse()) {
        $status = $e->getResponse()->getStatusCode();
        $body = $e->getResponse()->getBody()->getContents();
    }
    throw new Exception("API Error: $status - $body");
}

// POST JSON
$response = $client->post('users', [
    'json' => ['name' => 'John', 'email' => 'john@example.com'],
]);

// 多部分表單(檔案上傳)
$response = $client->post('upload', [
    'multipart' => [
        ['name' => 'file', 'contents' => fopen('/path/to/file.jpg', 'r'), 'filename' => 'avatar.jpg'],
        ['name' => 'user_id', 'contents' => '123'],
    ],
]);

// 非同步並發請求(Promise)
$promises = [
    'users' => $client->getAsync('users'),
    'posts' => $client->getAsync('posts'),
    'comments' => $client->getAsync('comments'),
];

$results = \GuzzleHttp\Promise\Utils::unwrap($promises);
// $results['users']->getStatusCode(), $results['users']->getBody()...

進階模式:重試、熔斷、快取中介軟體

<?php
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;

$stack = HandlerStack::create();

// 1. 指數退避重試
$stack->push(Middleware::retry(
    function ($retries, RequestInterface $request, $response = null, $exception = null) {
        if ($retries >= 3) return false;
        if ($exception) return true; // 網路錯誤重試
        if ($response && $response->getStatusCode() >= 500) return true; // 5xx 重試
        return false;
    },
    function ($retries) { return 100 * (2 ** $retries); } // 100ms, 200ms, 400ms
));

// 2. 請求/回應日誌
$stack->push(Middleware::log($logger, new \GuzzleHttp\MessageFormatter(
    "{hostname} {req_header_User-Agent} - \"{method} {uri} {version}\" {code} {res_header_Content-Length}"
)));

// 3. 快取(需 PSR-6/16 快取實作)
// $stack->push(Middleware::cache($cachePool));

$client = new Client(['handler' => $stack, 'base_uri' => 'https://api.example.com/']);

// 使用
$response = $client->get('users/123');

錯誤處理統一策略

<?php
class HttpClient {
    private Client $client;
    
    public function __construct(string $baseUri, array $options = []) {
        $this->client = new Client(array_merge([
            'base_uri' => $baseUri,
            'timeout' => 10,
            'http_errors' => false, // 不拋出 4xx/5xx 例外,統一處理
        ], $options));
    }
    
    public function request(string $method, string $uri, array $options = []): array {
        try {
            $response = $this->client->request($method, $uri, $options);
            $body = $response->getBody()->getContents();
            $data = $body ? json_decode($body, true) : null;
            
            if ($response->getStatusCode() >= 400) {
                return ['success' => false, 'status' => $response->getStatusCode(), 'error' => $data];
            }
            return ['success' => true, 'status' => $response->getStatusCode(), 'data' => $data];
        } catch (RequestException $e) {
            return ['success' => false, 'error' => $e->getMessage(), 'code' => $e->getCode()];
        }
    }
    
    public function get(string $uri, array $query = []): array {
        return $this->request('GET', $uri, ['query' => $query]);
    }
    
    public function post(string $uri, array $data = []): array {
        return $this->request('POST', $uri, ['json' => $data]);
    }
}

安全性檢查清單

  • SSL 驗證:生產環境必須 `verify_peer=true`、`verify_host=2`
  • 超時設定:連線與讀取超時分開設定,防止掛住
  • 敏感資訊不記錄:日誌中過濾 Authorization、API Key、密碼欄位
  • SSRF 防護:內部 API 呼叫驗證目標主機白名單,禁止存取內網元數據服務
  • 速率限制:客戶端實作 Token Bucket 或依賴 API 端限流回應
copyright © 萬盛學電腦網 all rights reserved