在 PHP 開發中,經常需要檢查遠端伺服器上的檔案是否存在,例如驗證圖片連結、檢查資源可用性等。本文介紹一種簡潔高效的方法,利用 file_get_contents 配合串流上下文來實現,避免下載整個檔案內容,節省頻寬與時間。
file_get_contents 函數支援 offset 和 maxlen 參數。我們只需讀取 1 個位元組(maxlen=1),若成功回傳非空字串即代表檔案存在;若回傳 false 則不存在。使用 @ 抑制錯誤訊息,配合三元運算子即可得到布林結果。
<?php
$file = "https://www.example.com/demo/file_exists.zip";
// 僅讀取 1 位元組,offset 設為 -1 表示從開頭讀取
$fileExists = @file_get_contents($file, null, null, -1, 1) ? true : false;
if ($fileExists) {
echo "File Exists!";
} else {
echo "Sorry, we couldn't find the file.";
}
?>
allow_url_fopen 為 On。false。若需更精確的 HTTP 狀態碼(如 301、403 等),建議使用 get_headers() 或 cURL 的 CURLOPT_NOBODY (HEAD 請求) 方式。