PHP 整合第三方 API、微服務溝通、網頁爬蟲都需要發送 HTTP 請求。本文比較三種主流方式:原生 `file_get_contents`、cURL 擴充、Guzzle HTTP Client,涵蓋 GET/POST、JSON、檔案上傳、超時、重試、錯誤處理。
| 特性 | file_get_contents | cURL | Guzzle |
|---|---|---|---|
| 依賴 | 核心(需 allow_url_fopen) | cURL 擴充 | Composer 套件 |
| HTTP 方法 | 僅 GET(需 stream context 支援 POST) | 完整支援 | 完整支援 |
| HTTPS/憑證 | 基本支援 | 完整控制 | 完整控制 |
| 超時控制 | stream context | 精確控制 | 精確控制 |
| 錯誤處理 | 回傳 false、觸發 warning | curl_error、curl_errno | 例外物件、PSR-7/18 |
| 並發/非同步 | 不支援 | curl_multi | Promise、非同步 |
| 中介軟體/擴充 | 無 | 無 | 豐富生態 |
| 推薦場景 | 簡單 GET、快速原型 | 底層控制、特殊協定 | 現代專案、API 整合、生產環境 |
<?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'; // 解析狀態碼
<?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',
],
]);
<?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]);
}
}