不下載檔案內容,僅發送 HTTP HEAD 請求解析 Content-Length 標頭,快速獲取遠程檔案大小。適用於下載前檢查、連結預覽、資源驗證。
function get_remote_filesize($url) {
if (empty($url)) return false;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_HEADER => true, // 返回頭部
CURLOPT_NOBODY => true, // HEAD 請求,不返回體
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true, // 跟隨重定向
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false, // 僅測試用,生產請驗證
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Filesize Bot)',
]);
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) return false;
// 解析 Content-Length
if (preg_match('/Content-Length:\s*(\d+)/i', $head, $m)) {
return (int)$m[1];
}
return false;
}
// 使用
$size = get_remote_filesize('https://example.com/video.mp4');
if ($size !== false) {
echo '大小: ' . number_format($size) . ' 位元組 (' . round($size/1024/1024, 2) . ' MB)';
} else {
echo '無法獲取大小(可能不支援 HEAD、需驗證、或重定向循環)';
}
| 選項 | 值 | 作用 |
|---|---|---|
CURLOPT_NOBODY | true | 發送 HEAD 請求,不下載 body |
CURLOPT_HEADER | true | 將回應頭包含在返回字符串中 |
CURLOPT_FOLLOWLOCATION | true | 自動跟隨 301/302 重定向 |
CURLOPT_MAXREDIRS | 5 | 限制重定向次數防循環 |
CURLOPT_TIMEOUT | 10 | 總超時秒數 |
CURLOPT_CONNECTTIMEOUT | 5 | 連線階段超時 |
function get_remote_filesize_native($url) {
$headers = @get_headers($url, 1);
if (!$headers) return false;
$cl = $headers['Content-Length'] ?? $headers['content-length'] ?? null;
return $cl ? (int)$cl : false;
}
缺點:不支援重定向跟隨控制、超時控制較弱、部分主機禁用 allow_url_fopen。
| 原因 | 現象 | 對策 |
|---|---|---|
| 伺服器不支援 HEAD | 返回 405/501 或無 Content-Length | 改用 GET + Range: bytes=0-0 讀取 1 字節推測 |
| 動態生成內容 | 無 Content-Length,用 Transfer-Encoding: chunked | 無法預知大小,需下載完才知 |
| 需登入/簽名 | 401/403 | 帶上 Cookie/Authorization header |
| 防盜鏈 Referer 檢查 | 403 | 設定 CURLOPT_REFERER |
| HTTPS 證書驗證失敗 | cURL error 60 | 設定 CURLOPT_CAINFO 或開發環境關閉驗證 |