專案整合第三方 API、微服務呼叫、遠端資源拉取等場景,皆屬「跨伺服器請求」。PHP 提供三種主流方式,各有優劣。
<?php
$url = 'https://api.example.com/data';
$response = file_get_contents($url);
// 需 php.ini: allow_url_fopen = On
stream_context_create() 設定 timeout、header、proxy@ 或錯誤處理器)<?php
$ch = curl_init('https://api.example.com/data');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => ['a' => 1, 'b' => 2],
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Authorization: Bearer xxx'],
]);
$response = curl_exec($ch);
if ($response === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
curl_close($ch);
php-curl 擴展<?php
$fp = fopen('https://api.example.com/large.csv', 'r');
if ($fp) {
while (!feof($fp)) {
$line = fgets($fp, 1024);
// 處理單行,適合大檔案串流
}
fclose($fp);
}
allow_url_fopen = On| 維度 | file_get_contents | cURL | fopen |
|---|---|---|---|
| 支援 HTTP Method | GET(POST 需 context) | 全部 | GET |
| 錯誤處理 | 弱 | 完整 | 中 |
| 大檔案記憶體 | 全載入 | 可串流 | 逐行最省 |
| 效能 | 中 | 高 | 中 |
| 生產推薦度 | 簡單 GET | ⭐⭐⭐⭐⭐ | 大檔下載 |
get()、post()、request() 介面。CURLOPT_TIMEOUT(連線)與 CURLOPT_CONNECTTIMEOUT(總計),防止阻塞。CURLOPT_SSL_VERIFYPEER 驗證憑證,生產環境嚴禁關閉。curl_multi_* 或 Swoole/OpenSwoole 協程客戶端。