在 PHP 中獲取遠程文件大小(不下載整個文件)是常見需求,如下載管理器、文件驗證、存儲配額檢查。本文對比三種方案的優劣與適用場景。
<?php
function getRemoteSizeFileGetContents($url) {
$content = @file_get_contents($url);
if ($content === false) return false;
return strlen($content);
}
?>
缺點:會下載整個文件到內存,大文件極易導致內存溢出(OOM)、超時。僅適用於極小文件(<1MB)或本地文件。
<?php
function getRemoteSizeGetHeaders($url) {
// 關鍵:第二參數 true 返回關聯數組,且自動跟隨重定向
$headers = @get_headers($url, true);
if (!$headers) return false;
// Content-Length 可能在數組中(多次重定向時)
$contentLength = $headers['Content-Length'] ?? null;
if (is_array($contentLength)) {
// 取最後一次響應的 Content-Length
$contentLength = end($contentLength);
}
return $contentLength ? (int)$contentLength : false;
}
?>
優點:僅發送 HEAD 請求,不下載 Body,速度快、內存佔用極低。
前提:服務器必須支援 HEAD 方法並返回 Content-Length;PHP 需開啟 allow_url_fopen=On。
<?php
function getRemoteSizeSocket($url, $timeout = 10) {
$parsed = parse_url($url);
if (!$parsed || !isset($parsed['host'])) return false;
$host = $parsed['host'];
$port = $parsed['port'] ?? ($parsed['scheme'] === 'https' ? 443 : 80);
$path = $parsed['path'] ?? '/';
if (isset($parsed['query'])) $path .= '?' . $parsed['query'];
// HTTPS 需用 ssl:// 或 tls:// 前綴
$socketHost = ($parsed['scheme'] === 'https') ? "ssl://$host" : $host;
$fp = @fsockopen($socketHost, $port, $errno, $errstr, $timeout);
if (!$fp) return false;
stream_set_timeout($fp, $timeout);
// 發送 HEAD 請求
$request = "HEAD $path HTTP/1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($fp, $request);
// 讀取響應頭
$headers = '';
while (!feof($fp)) {
$line = fgets($fp, 4096);
$headers .= $line;
if (trim($line) === '') break; // 頭部結束
}
fclose($fp);
// 解析 Content-Length
if (preg_match('/Content-Length:\s*(\d+)/i', $headers, $matches)) {
return (int)$matches[1];
}
return false;
}
?>
優點:不依賴 allow_url_fopen,支援 HTTPS,可自定義超時、Header、代理,適合受限環境。
缺點:代碼較繁瑣,需手動處理重定向、Chunked 編碼、SSL 驗證等細節。
| 維度 | file_get_contents | get_headers | fsockopen |
|---|---|---|---|
| 內存佔用 | 高(整文件) | 極低 | 極低 |
| 速度 | 慢(下載全文) | 快(HEAD 請求) | 快(HEAD 請求) |
| 依賴配置 | allow_url_fopen | allow_url_fopen | 無(需 sockets 擴展) |
| HTTPS 支援 | 是 | 是 | 是(ssl://) |
| 重定向處理 | 自動 | 自動 | 手動 |
| 推薦場景 | 極小文件/本地 | 通用首選 | 受限環境/需精細控制 |
<?php
function getRemoteFileSize($url) {
// 1. 優先嘗試 get_headers(最簡潔高效)
if (ini_get('allow_url_fopen')) {
$size = getRemoteSizeGetHeaders($url);
if ($size !== false) return $size;
}
// 2. 降級到 Socket 方案
return getRemoteSizeSocket($url);
}
// 使用示例
$url = 'https://example.com/large-file.zip';
$size = getRemoteFileSize($url);
if ($size !== false) {
echo "文件大小: " . number_format($size / 1024 / 1024, 2) . " MB";
} else {
echo "無法獲取文件大小";
}
?>
Content-Length,需下載計算或放棄。get_headers 自動跟隨;Socket 需手動解析 Location 並重新請求。float。