file_get_contents 從 PHP 5.0 起支援 context 參數,可精確控制 HTTP 行為(超時、POST、Header 等)。set_time_limit 僅限制腳本總執行時間,不影響網路讀取超時。
$opts = [
'http' => [
'method' => 'GET',
'timeout' => 3, // 秒
]
];
$context = stream_context_create($opts);
// 重試機制:最多嘗試 3 次
$cnt = 0;
while ($cnt < 3 && ($content = file_get_contents('https://example.com', false, $context)) === false) {
$cnt++;
usleep(200000); // 200ms 間隔
}
if ($content !== false) {
echo '成功取得內容,長度:' . strlen($content);
} else {
echo '重試 3 次仍失敗';
}
function httpPost($url, array $data, $timeout = 10) {
$context = [
'http' => [
'method' => 'POST',
'timeout' => $timeout,
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query($data),
]
];
return file_get_contents($url, false, stream_context_create($context));
}
// 使用範例
$response = httpPost('https://api.example.com/endpoint', [
'name' => 'test',
'email' => 'admin@example.com',
], 5);
fopen、file、fsockopen(建議搭配 stream_set_timeout)curl 系列(有獨立的 CURLOPT_TIMEOUT、CURLOPT_CONNECTTIMEOUT)timeout 僅控制讀取;若需控制連線階段,需用 fsockopen 或 cURL。sleep(pow(2, $retry) * 100000) 避免雪崩效應。curl_multi)。| 錯誤 | 可能原因 |
|---|---|
| Connection timed out | 防火牆阻擋、目標主機不可達、DNS 解析失敗 |
| SSL certificate problem | CA 憑證缺失、憑證過期、域名不符 |
| HTTP 500/502/503/504 | 伺服器端錯誤、閘道超時、服務不可用 |