通過 fsockopen 建立 TCP 連接,發送 HTTP/1.1 HEAD 請求,僅獲取響應頭中的 Content-Length,避免下載整個文件,極適合大文件、批量鏈接檢測場景。
<?php
function getFileSize($url) {
$url = parse_url($url);
$host = $url['host'];
$port = $url['port'] ?? 80;
$path = $url['path'] ?? '/';
if (!$fp = @fsockopen($host, $port, $errno, $errstr, 10)) {
return null; // 連接失敗
}
// 發送 HEAD 請求
fputs($fp, "HEAD $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Connection: Close\r\n\r\n");
// 讀取響應頭
while (!feof($fp)) {
$line = fgets($fp);
if (trim($line) === '') break; // 頭部結束
if (preg_match('/Content-Length:\s*(\d+)/i', $line, $matches)) {
fclose($fp);
return (int)$matches[1]; // 返回字節數
}
}
fclose($fp);
return null; // 無 Content-Length (如分塊傳輸)
}
// 測試
echo getFileSize("https://www.jb51.net/images/logo.gif"); // 4445
?>
feof() 阻塞。fsockopen 第 5 參數設置連接超時 (秒)。Content-Length,函數返回 null,需改用 GET 範圍請求或下載統計。fsockopen 改為 stream_socket_client('ssl://host:443') 或用 cURL。function getFileSizeCurl($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true, // HEAD 請求
CURLOPT_HEADER => true, // 包含頭
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true, // 跟隨重定向
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false, // 測試環境
]);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
return $size > 0 ? (int)$size : null;
}
cURL 支持 HTTPS、重定向、代理、並發,生產環境首選。
Content-Length: 0 或 404。輕量、高效、不佔用磁盤 IO,是遠程文件大小獲取的標準姿勢。