後端服務間調用、抓取遠程頁面、調用第三方 API,PHP 提供了三種原生方式發起 HTTP 請求。
file_get_contents()(最簡單)$url = 'https://www.example.com';
$response = file_get_contents($url);
echo $response;
前提: php.ini 中 allow_url_fopen = On。
缺點: 無法自定義 Header、超時、POST 數據、Cookie、處理重定向等,不適合生產環境複雜交互。
$url = 'https://www.example.com/api';
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true, // 返回字符串而非直接輸出
CURLOPT_HEADER => false, // 不包含響應頭
CURLOPT_TIMEOUT => 10, // 總超時秒數
CURLOPT_CONNECTTIMEOUT => 5, // 連接超時
CURLOPT_FOLLOWLOCATION => true, // 自動跟隨 3xx 重定向
CURLOPT_MAXREDIRS => 5, // 最大重定向次數
CURLOPT_USERAGENT => 'MyApp/1.0 (PHP/cURL)', // 標識客戶端
CURLOPT_SSL_VERIFYPEER => true, // 生產環境務必驗證 SSL 證書
CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
if ($response === false) {
$errno = curl_errno($ch);
$error = curl_error($ch);
// 記錄錯誤、拋出異常、降級處理...
}
curl_close($ch);
// 處理響應
$data = json_decode($response, true);
| 選項 | 用途 |
|---|---|
CURLOPT_POST | 啟用 POST 請求 |
CURLOPT_POSTFIELDS | POST 數據(陣列自動編碼為 multipart/form-data;字符串發送 application/x-www-form-urlencoded) |
CURLOPT_HTTPHEADER | 自定義請求頭(如 ['Content-Type: application/json', 'Authorization: Bearer xxx']) |
CURLOPT_COOKIE / CURLOPT_COOKIEJAR/FILE | 發送/持久化 Cookie |
CURLOPT_PROXY | 代理服務器 |
CURLOPT_WRITEFUNCTION | 流式處理大響應體(回調函數) |