file_get_contents 預設無超時限制,網絡波動時會長時間阻塞。透過 stream_context_create 設定 HTTP 上下文參數,可精確控制超時與重試邏輯。
$url = 'https://api.example.com/data';
$opts = [
'http' => [
'method' => 'GET',
'timeout' => 3, // 秒,連線與讀取總超時
'ignore_errors' => true, // 即使 4xx/5xx 也取得內容
],
'ssl' => [
'verify_peer' => false, // 僅測試環境建議,生產請驗證
'verify_peer_name' => false,
]
];
$context = stream_context_create($opts);
$content = @file_get_contents($url, false, $context);
if ($content === false) {
// 記錄錯誤、重試或降級處理
error_log("請求失敗: $url");
}
function fetchWithRetry($url, $maxRetries = 3, $timeout = 2) {
$opts = ['http' => ['method' => 'GET', 'timeout' => $timeout]];
$context = stream_context_create($opts);
for ($i = 0; $i < $maxRetries; $i++) {
$content = @file_get_contents($url, false, $context);
if ($content !== false) return $content;
usleep(200000); // 200ms 退避
}
return false;
}
| 參數 | 說明 |
|---|---|
| timeout | 浮點數,單位秒,適用於連線與讀取階段 |
| method | GET、POST 等 HTTP 方法 |
| header | 自定義請求標頭,如 API Key |
| ignore_errors | true 時非 2xx 狀態碼也會回傳內容 |
提示:高併發或複雜場景建議改用 cURL 或 Guzzle,支援更豐富的超時控制(連線超時、傳輸超時分離)、非同步請求、中間件等。