PHP 取得遠端資料常見三種方式,各有優缺點與適用場景。本文以統一範例對比差異,並說明常見失敗排查方向。
$url = 'https://api.example.com/data';
$ctx = stream_context_create(['http' => ['timeout' => 10, 'method' => 'GET']]);
$response = @file_get_contents($url, false, $ctx);
if ($response === false) { /* 錯誤處理 */ }
allow_url_fopen=On 才能用;無法精細控制 SSL 驗證、Header、Cookie、重導向追蹤;大檔案記憶體壓力大。$ch = curl_init('https://api.example.com/data');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => true, // 生產環境建議 true + CA 憑證
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_USERAGENT => 'MyApp/1.0',
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
$fp = @fopen('https://api.example.com/data', 'rb');
if (!$fp) { /* 失敗 */ }
$response = '';
while (!feof($fp)) {
$response .= fread($fp, 8192);
}
fclose($fp);
allow_url_fopen、錯誤處理麻煩、無法精細控制 SSL/Header。allow_url_fopen=Off → 改用 cURL 或開啟設定。/etc/resolv.conf。| 場景 | 推薦 |
|---|---|
| 簡單 GET、小資料、開發測試 | file_get_contents |
| 生產環境、需 Header/Cookie/SSL/POST/並發 | cURL |
| 超大檔案下載/串流、記憶體受限 | fopen + fread / cURL 寫檔 |