| 目的 | 方法 | 特點 |
| 瀏覽器跳轉 (客戶端) | header('Location: ...') | 302/301 重定向,瀏覽器地址欄變化,GET 請求 |
| 服務端獲取內容 | file_get_contents()、cURL、Guzzle | 後端代理請求,用戶無感,支援 POST/Headers/超時控制 |
| 服務端轉發/代理 | cURL/Guzzle + 輸出響應 | 隱藏上游地址、聚合多服務、协議轉換 |
方法對比與代碼範例
1. header() 重定向 (僅適用跳轉)
<?php
// 必須在任何輸出前
header('Location: https://example.com/target', true, 302); // 301 永久、302 臨時
exit(); // 關鍵:阻止後續代碼執行
2. file_get_contents() 簡單 GET
<?php
// 需 php.ini: allow_url_fopen = On
$url = 'https://api.example.com/data?key=value';
$context = stream_context_create([
'http' => [
'timeout' => 10, // 秒
'user_agent' => 'MyApp/1.0',
'header' => "Accept: application/json\r\n",
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
],
]);
$response = @file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception("請求失敗: $url");
}
$data = json_decode($response, true);
3. cURL 完整功能 (推薦生產環境)
<?php
function httpRequest(string $url, array $options = []): array
{
$ch = curl_init();
$defaultOptions = [
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://myapp.com)',
CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
];
// 合併用戶選項
curl_setopt_array($ch, $defaultOptions + $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 錯誤 [$errno]: $error");
}
return [
'status' => $info['http_code'],
'headers' => $info['header_size'] ? substr($response, 0, $info['header_size']) : '',
'body' => substr($response, $info['header_size']),
'info' => $info,
];
}
// 使用示例
// GET
$result = httpRequest('https://api.example.com/users');
// POST JSON
$result = httpRequest('https://api.example.com/users', [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(['name' => '張三']),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer token123',
],
]);
// 上傳文件
$result = httpRequest('https://api.example.com/upload', [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'file' => new CURLFile('/path/to/file.jpg', 'image/jpeg', 'avatar.jpg'),
'user_id' => 123,
],
]);
4. Guzzle HTTP Client (現代 PHP 首選)
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://api.example.com/',
'timeout' => 10.0,
'headers' => [
'User-Agent' => 'MyApp/1.0',
'Accept' => 'application/json',
],
// 中間件:重試、日誌、認證
'handler' => \GuzzleHttp\HandlerStack::create(
new \GuzzleHttp\Middleware\RetryMiddleware(3, 100) // 簡化示意
),
]);
try {
// GET
$response = $client->get('users', ['query' => ['page' => 1]]);
// POST JSON
$response = $client->post('users', [
'json' => ['name' => '李四', 'email' => 'li4@example.com'],
'headers' => ['Authorization' => 'Bearer token123'],
]);
// 多併發請求 (異步)
$promises = [
'users' => $client->getAsync('users'),
'posts' => $client->getAsync('posts'),
];
$results = \GuzzleHttp\Promise\Utils::unwrap($promises);
$data = json_decode($response->getBody()->getContents(), true);
} catch (RequestException $e) {
if ($e->hasResponse()) {
$status = $e->getResponse()->getStatusCode();
$body = $e->getResponse()->getBody()->getContents();
}
// 記錄日誌、拋出業務異常
}
進階場景處理
超時控制策略
<?php
// 連接超時 vs 讀取超時
$options = [
CURLOPT_CONNECTTIMEOUT_MS => 2000, // 2秒建立連接
CURLOPT_TIMEOUT_MS => 5000, // 5秒完成整個請求
// 或 DNS 緩存
CURLOPT_DNS_CACHE_TIMEOUT => 300, // 5分鐘緩存 DNS
];
證書驗證與安全
<?php
// 生產環境必須驗證
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => '/etc/ssl/certs/ca-certificates.crt', // 指定 CA 憑證包
// 內網/測試環境可關閉 (不推薦生產)
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
大文件流式下載 (避免記憶體爆炸)
<?php
$fp = fopen('/tmp/large-file.zip', 'wb');
$ch = curl_init('https://example.com/large-file.zip');
curl_setopt_array($ch, [
CURLOPT_FILE => $fp,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 3600,
CURLOPT_NOPROGRESS => false,
CURLOPT_PROGRESSFUNCTION => function ($ch, $dltotal, $dlnow) {
if ($dltotal > 0) {
printf("\r下載進度: %.2f%%", ($dlnow / $dltotal) * 100);
}
},
]);
curl_exec($ch);
curl_close($ch);
fclose($fp);
選型決策樹
需要瀏覽器跳轉? → header('Location: ...')
↓ 否
簡單 GET、無依賴、PHP 7.4+? → file_get_contents() + stream_context
↓ 否
需要 POST/Headers/超時/重試/並發/代理/證書/流式? → Guzzle (composer require guzzlehttp/guzzle)
↓ 否
舊項目無 Composer、需精細控制 cURL 選項? → 封裝 curl 函數庫
常見坑點
allow_url_fopen=Off 導致 file_get_contents 失效 → 改用 cURL/Guzzle
- 未設置
CURLOPT_RETURNTRANSFER 導致直接輸出
- HTTPS 證書驗證失敗 → 更新 CA 憑證包、檢查系統時間、正確配置
CURLOPT_CAINFO
- 大響應體導致 OOM → 流式處理、分塊讀取
- 並發請求阻塞 → Guzzle 異步 + Promise、Swoole 协程 HTTP Client
copyright ©
萬盛學電腦網 all rights reserved