在實現跨站點用戶資料同步時,使用 file_get_contents 抓取遠端頁面常面臨連線逾時導致 Fatal Error,或回應過慢阻塞後續程式執行。本文深入分析兩種解決方案的實測表現。
<?php
$url = "https://example.com/api.php";
$ctx = stream_context_create([
'http' => ['timeout' => 10]
]);
$result = @file_get_contents($url, 0, $ctx);
if ($result) {
var_dump($result);
} else {
echo "Buffer is empty";
}
?>
實測結論:本地環境表現良好,但跨國請求(如中國大陸訪問美國伺服器)幾乎必現超時,timeout 參數在外網環境下往往失效。
<?php
function zhoz_get_contents($url, $second = 5) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $second); // 總超時時間
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $second); // 連線超時時間
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
// 使用範例
$url = "https://example.com/api.php";
try {
echo date('Y-m-d H:i:s') . "\n";
$buffer = zhoz_get_contents($url);
echo date('Y-m-d H:i:s') . "\n";
if (empty($buffer)) {
echo "Buffer is empty";
} else {
echo "Buffer is not empty";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
| 特性 | stream_context + file_get_contents | cURL |
|---|---|---|
| 外網穩定性 | 差(常失效) | 優(精確控制) |
| 連線/總超時分離 | 不支援 | 支援 |
| HTTP 狀態碼獲取 | 困難 | 容易 |
| 重導向處理 | 預設跟隨 | 可精細控制 |
| SSL 憑證驗證 | 有限控制 | 完整控制 |
<?php
function get_remote_content($url, $timeout = 10) {
// 1. 優先嘗試 cURL(最穩定)
if (function_exists('curl_init')) {
return zhoz_get_contents($url, $timeout);
}
// 2. 回退:串流上下文(需 allow_url_fopen)
if (ini_get('allow_url_fopen')) {
$ctx = stream_context_create(['http' => ['timeout' => $timeout]]);
return @file_get_contents($url, 0, $ctx);
}
return false;
}
?>
針對跨網段、高延遲的遠端請求,cURL 是唯一可靠選擇。建議專案統一封裝 HTTP 客戶端,內部使用 cURL,並提供超時、重試、錯誤處理等企業級特性。