非常簡單的函式,用於取得易於理解的檔案大小。
<?php
function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
filesize — 取得檔案大小
filename
檔案的路徑。
傳回檔案大小,單位為位元組,或者在發生錯誤時傳回 false
(並產生層級為 E_WARNING
的錯誤)。
注意事項:由於 PHP 的整數類型是有號數,且許多平台使用 32 位元整數,因此某些檔案系統函式對於大於 2GB 的檔案可能會返回非預期的結果。
失敗時,會發出 E_WARNING
。
範例 #1 filesize() 範例
<?php
// 輸出例如 somefile.txt: 1024 位元組
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' 位元組';
?>
注意事項:此函式的結果會被快取。詳情請參閱 clearstatcache()。
非常簡單的函式,用於取得易於理解的檔案大小。
<?php
function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
如果您最近在檔案中附加了某些內容,然後關閉了它,則此方法將不會顯示附加的資料。
<?php
// 將檔案內容讀取到字串中
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
您應該在呼叫 filesize() 之前先呼叫 clearstatcache()
我花了兩個小時才找到 =/
<?php
// 取得所有大於 4GB 的檔案大小。
// 適用於 32 位元和 64 位元的 PHP,並支援 Linux
// 使用 com_dotnet 擴充套件
function getSize($file) {
$size = filesize($file);
if ($size <= 0)
if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')) {
$size = trim(`stat -c%s $file`);
}
else{
$fsobj = new COM("Scripting.FileSystemObject");
$f = $fsobj->GetFile($file);
$size = $f->Size;
}
return $size;
}
?>
這是從 rommel at rommelsantor dot com 取得的函式稍微修改後的版本。現在它會回傳兩個字元的檔案大小,更容易閱讀。
<?php
函式 human_filesize($bytes, $decimals = 2) {
$factor = floor((strlen($bytes) - 1) / 3);
如果 ($factor > 0) $sz = 'KMGT';
返回 sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor - 1] . 'B';
}
print human_filesize(12, 0); // 12B
print human_filesize(1234567890, 4); // 1.1498GB
print human_filesize(123456789, 1); // 117.7MB
print human_filesize(12345678901234, 5); // 11.22833TB
print human_filesize(1234567, 3); // 1.177MB
print human_filesize(123456); // 120.56KB
?>
我移除了 P 單位,因為 strlen 對於超過 14 位數的整數似乎無法正常運作。雖然這可能只是我系統的限制。
第一個範例可能會讓人以為這個函式適用於本機檔案名稱,例如 $fs = filesize("error_log"),但如果您手動刪除一些文字,然後儲存並關閉檔案,下次您檢查 filesize("error_log") 時,它會傳回原始值,因為該值已快取以提升效能。如果您不知道這一點,它看起來就像一個棘手的錯誤。
所以,大家都告訴您要插入 clearstatcache(),它應該清除快取的值並允許您擷取目前的檔案大小,但它仍然沒有作用,看起來像另一個錯誤!
然而,我發現如果您總是指定完整路徑
例如 $fs = filesize("/user/some/path/error_log");
則不需要 clearstatcache()。
<?php
/**
* 將位元組轉換為人類可讀的檔案大小。
*
* @param string $bytes
* @return string 人類可讀的檔案大小 (例如:2.87 MB)
* @author Mogilev Arseny
*/
function FileSizeConvert($bytes)
{
$bytes = floatval($bytes);
$arBytes = array(
0 => array(
"UNIT" => "TB",
"VALUE" => pow(1024, 4)
),
1 => array(
"UNIT" => "GB",
"VALUE" => pow(1024, 3)
),
2 => array(
"UNIT" => "MB",
"VALUE" => pow(1024, 2)
),
3 => array(
"UNIT" => "KB",
"VALUE" => 1024
),
4 => array(
"UNIT" => "B",
"VALUE" => 1
),
);
foreach($arBytes as $arItem)
{
if($bytes >= $arItem["VALUE"])
{
$result = $bytes / $arItem["VALUE"];
$result = str_replace(".", ".", strval(round($result, 2)))." ".$arItem["UNIT"];
break;
}
}
return $result;
}
?>
這個函式也適用於瀏覽器快取控制。例如,您有一個樣式表,並且希望確保每個人都擁有最新版本。您可以每次編輯時都重新命名它,但這會浪費時間。您可以這樣做:
<?php
echo '<link rel="stylesheet" href="style.css?ver=1.'.filesize(dirname(__FILE__).'/style.css').'.'.filemtime(dirname(__FILE__).'/style.css').'.0">';
?>
範例輸出
<link rel="stylesheet" href="style.css?ver=1.8824.1499869132.0">
這也可以應用於 JS 和同名的圖片。
若檔案大於 2 GB,請使用我的函式庫 Big File Tools。https://github.com/jkuchar/BigFileTools. 更多細節請參考 Stack Overflow:http://stackoverflow.com/a/35233556/631369
<?php
/**
* 取得檔案大小(即使檔案大於 2 GB)
* 對於超過 PHP_INT_MAX (2,147,483,647) 的檔案大小,PHP 的 filesize 函式會從 -PHP_INT_MAX 迴圈到 PHP_INT_MAX。
*
* @param string $path 檔案路徑
* @return mixed 檔案大小,若發生錯誤則回傳 false
*/
function realFileSize($path)
{
if (!file_exists($path))
return false;
$size = filesize($path);
if (!($file = fopen($path, 'rb')))
return false;
if ($size >= 0)
{//檢查是否真的是小檔案(小於 2 GB)
if (fseek($file, 0, SEEK_END) === 0)
{//真的是小檔案
fclose($file);
return $size;
}
}
//使用 fseek 快速跳過前 2 GB。之後,fseek 在 32 位元 PHP 上無法運作(它在內部使用 int)
$size = PHP_INT_MAX - 1;
if (fseek($file, PHP_INT_MAX - 1) !== 0)
{
fclose($file);
return false;
}
$length = 1024 * 1024;
while (!feof($file))
{//讀取檔案直到結束
$read = fread($file, $length);
$size = bcadd($size, $length);
}
$size = bcsub($size, $length);
$size = bcadd($size, strlen($read));
fclose($file);
return $size;
}
// 將負數檔案大小最佳轉換
// 不適用於大於 4GB 的檔案
//
// 尤其是 32 位元系統。檔案大小轉換限制為 4GB 或
// 4,294,967,296。為什麼我們會得到負數?因為檔案
// 指標計數器必須使用 PHP 的最大值 2,147,483,647。
// 檔案偏移量:0、1、2、3、...、2,147,483,647 = 2GB
// 要超過 4GB,則使用負數
// 因此,在 2,147,483,647 之後,我們會得到 -2,147,483,647
// -2147483647, -2147483646, -2147483645, -2147483644 ... 0 = 4GB
// therefore 0, 2147483647 and -2147483647 to 0. all done 4GB = 4294967296
// the first offset to 0 and the last offset to 0 of 4GB should be added in
// your compute, so "+ 2" for the number of bytes exate .
<?php
function filsize_32b($file) {
$filez = filesize($file);
if($filez < 0) { return (($filez + PHP_INT_MAX) + PHP_INT_MAX + 2); }
else { return $filez; }
}
?>
The simplest and most efficient implemention for getting remote filesize
<?php
function remote_filesize($url) {
static $regex = '/^Content-Length: *+\K\d++$/im';
if (!$fp = @fopen($url, 'rb')) {
return false;
}
if (
isset($http_response_header) &&
preg_match($regex, implode("\n", $http_response_header), $matches)
) {
return (int)$matches[0];
}
return strlen(stream_get_contents($fp));
}
?>
This function quickly calculates the size of a directory
http://aidanlister.com/repos/v/function.dirsize.php
You can convert filesizes to a human readable size using
http://aidanlister.com/repos/v/function.size_readable.php
For a faster (unix only) implementation, see function.disk-total-space, note #34100
https://php.dev.org.tw/manual/en/function.disk-total-space.php#34100
Also of interest is this wikipedia article, discussing the difference between a kilobyte (1000) and a kibibyte (1024).
http://en.wikipedia.org/wiki/Bytes
Here is my super fast method of getting >2GB files to output the correct byte size on any version of windows works with both 32Bit and 64Bit.
<?php
函數 find_filesize($file)
{
if(substr(PHP_OS, 0, 3) == "WIN")
{
exec('for %I in ("'.$file.'") do @echo %~zI', $output);
$return = $output[0];
}
else
{
$return = filesize($file);
}
return $return;
}
//用法: find_filesize("路徑");
//範例:
echo "檔案大小為: ".find_filesize("D:\Server\movie.mp4")."";
?>
// 使用 Windows 10 的 dir 指令擷取檔案大小
// 適用於所有 32/64 位元系統,並且與 Dummy 檔案有最佳的相容性
// 但無法以 (int) 整數型態回傳值,最佳回傳型態為浮點數 (Float)
<?php
filesize_dir("d:\\test.mkv"); //11.5GB => 回傳 (float) 12401880207
函數 filesize_dir($file) {
exec('dir ' . $file, $inf);
$size_raw = $inf[6];
$size_exp = explode(" ",$size_raw);
$size_ext = $size_exp[19];
$size_int = (float) str_replace(chr(255), '', $size_ext);
return $size_int;
}
?>
此函數會回傳 32 位元作業系統上大於 2 GB 檔案的精確檔案大小。
<?php
function file_get_size($file) {
//開啟檔案
$fh = fopen($file, "r");
//宣告一些變數
$size = "0";
$char = "";
//將檔案指標設定為 0;我有點過於謹慎,您可以移除這行
fseek($fh, 0, SEEK_SET);
//將乘數設定為零
$count = 0;
while (true) {
//在檔案中向前跳轉 1 MB
fseek($fh, 1048576, SEEK_CUR);
//檢查是否真的離開了檔案
if (($char = fgetc($fh)) !== false) {
//如果不是,則繼續
$count ++;
} else {
//否則跳回離開前的檔案位置並退出迴圈
fseek($fh, -1048576, SEEK_CUR);
break;
}
}
//我們可以進行 $count 次跳轉,因此檔案至少有 $count * 1.000001 MB 大
//1048577 因為我們跳轉 1 MB 且 fgetc 也前進 1 B
$size = bcmul("1048577", $count);
//現在計算最後幾個位元組;它們總是小於 1048576,所以速度相當快
$fine = 0;
while(false !== ($char = fgetc($fh))) {
$fine ++;
}
//並將它們相加
$size = bcadd($size, $fine);
fclose($fh);
return $size;
}
?>
<?php
function getSizeFile($url) {
if (substr($url,0,4)=='http') {
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
else { $x = $x['content-length']; }
}
else { $x = @filesize($url); }
return $x;
}
?>
如果伺服器端有重新導向 (例如 .htaccess 中的 Redirect Permanent)
例如在這種情況下,我們會有
[content-length] => 陣列
(
[0] => 294 // 請求檔案的大小
[1] => 357556 // 重新導向後檔案的實際大小
)
在 Windows 10 下,`filesize` 顯然無法使用相對路徑。請改用絕對路徑。 `$size = filesize(".\\myfile.txt");` 對我來說無效,而 `"d:\\MyFiles\\Myfile.txt"` 則可以。同樣的狀況也適用於類似 `is_file()` 或 `stat()` 等函數。除非給定絕對路徑,否則它們將無法正常運作。
// 使用系統 Windows 指令來取得檔案大小
// 最適用於 32 位元或 64 位元的 PHP
// 我不知道它是否適用於其他 Windows 版本,但在 Windows 10 上運作良好
<?php
echo filesize_cmd('c:\\', 'log.txt'); //返回 1135
function filesize_cmd($folder, $file) {
return exec('forfiles /p '.$folder.' /m "'.$file.'" /c "cmd /c echo @fsize"');
}
?>
function dir_size($file) {
//在 Win 7 x64 php 5.4 上測試過
exec('dir /s /a "' . $file.'"', $inf);
$r=explode(' ',$inf[count($inf)-2]);
$rr = preg_replace('~[^\d]+~','',$r[count($r)-2]);
return $rr;
}
我建立了一個方便的函數,使用 kaspernj at gmail dot com 和 md2perpe at gmail dot com 的部分程式碼,它應該可以在 Windows、Linux 和 Mac(至少)上取得大於 4GB 的檔案大小。
<?php
函式 getSize($file) {
$size = filesize($file);
if ($size < 0)
if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'))
$size = trim(`stat -c%s $file`);
else{
$fsobj = new COM("Scripting.FileSystemObject");
$f = $fsobj->GetFile($file);
$size = $file->Size;
}
return $size;
}
?>
<?php
// 快速範例,用於測試回傳值,以區分 0 位元組的檔案和 filesize() 呼叫失敗的情況
$size = filesize("some.file");
if ($size === FALSE) {
echo "無法取得檔案大小";
} else {
echo "some.file 的大小為 $size 位元組";
}
// 更簡潔的版本,略有不同
if ( ($size = filesize("some.file")) !== FALSE)
echo "some.file 的大小為 $size 位元組";
?>
在 32 位元 PHP 環境下,快速取得大檔案 (>2GB) 實際檔案大小的實作方法
函式 RealFileSize($fp)
{
$pos = 0;
$size = 1073741824;
fseek($fp, 0, SEEK_SET);
while ($size > 1)
{
fseek($fp, $size, SEEK_CUR);
if (fgetc($fp) === false)
{
fseek($fp, -$size, SEEK_CUR);
$size = (int)($size / 2);
}
else
{
fseek($fp, -1, SEEK_CUR);
$pos += $size;
}
}
while (fgetc($fp) !== false) $pos++;
return $pos;
}
輸入是一個已開啟的檔案控制代碼。回傳值是一個整數 (檔案大小 < 4GB) 或浮點數 (檔案大小 ≥ 4GB)。
這個方法一開始會一次跳過約 1GB,讀取一個字元,然後重複。當它進入最後一個 GB 時,如果讀取失敗,它會將大小減半。最後幾個位元組會直接讀取。
有些人可能會擔心這個函式的問題,因為當超過整數限制後,`$pos` 會變成浮點數,而他們知道浮點數容易不精確。在大多數正確實作 IEEE 浮點數規範的電腦上,`$pos` 在 9 PB 左右的範圍內都能保持精確。除非您在 PHP 中處理數 PB 的檔案,或者程式碼在奇怪的硬體上執行,否則這個函式應該非常夠用。這個函式的每個部分都經過精心設計,以處理 32 位元的缺陷。
以下是一個以人類易懂的方式取得檔案大小的函式,包含小數點、千分位符號、小數位數等等。
function convertFileSize($file, $size=null, $decimals=2, $dec_sep='.', $thousands_sep=','){
if (!is_file($file)){
return "檔案不存在"; // Translated from "El fichero no existe"
}
$bytes = filesize($file);
$sizes = 'BKMGTP';
if (isset($size)){
$factor = strpos($sizes, $size[0]);
if ($factor===false){
return "大小單位必須是 B, K, M, G, T 或 P"; // Translated from "El tamaño debe ser B, K, M, G, T o P"
}
} else {
$factor = floor((strlen($bytes) - 1) / 3);
$size = $sizes[$factor];
}
return number_format($bytes / pow(1024, $factor), $decimals, $dec_sep, $thousands_sep).' '.$size;
}
來源:http://softontherocks.blogspot.com/2014/11/obtener-el-tamano-de-un-fichero-y.html
<?php
// Windows 的檔案大小
// 如果 filesize() php > PHP_INT_MAX (4 294 967 296) :: 會失敗
// filesize_cmd 傳回 Windows 測量的值
function filesize_cmd($file) {
$pth = pathinfo($file);
$fz = filesize($file);
$fx = exec('forfiles /p ' . $pth['dirname'] . ' /m "' . $pth['basename'] . '" /c "cmd /c echo @fsize"');
if($fz != $fx) { return $fx; }
return $fz;
}
?>
我有一個正在執行的 CLI 腳本,它在 ssh2_sftp 連線上使用 filesize 函式。它有 >2GB 的限制問題,但在本地沒有這個問題。我設法透過 ssh2_shell 執行「du -sb」命令來解決這個問題。
以下函式以 ssh2_connect 資源和路徑作為輸入。它可能不太簡潔,但目前解決了這個問題。
<?php
函式 fSSHFileSize($oConn, $sPath) {
如果(false !== ($oShell = @ssh2_shell($oConn, 'xterm', null, 500, 24, SSH2_TERM_UNIT_CHARS))) {
fwrite($oShell, "du -sb '".$sPath."'".PHP_EOL);
sleep(1);
while($sLine = fgets($oShell)) {
flush();
$aResult[] = $sLine;
}
fclose($oShell);
$iSize = 0;
如果(count($aResult) > 1) {
$sTemp = $aResult[count($aResult)-2];
$sSize = substr($sTemp, 0, strpos($sTemp, chr(9)));
如果(is_numeric(trim($sSize))) {
$iTemp = (int)$sSize;
如果($iTemp > "2000000000") $iSize = $iTemp;
}
}
回傳 $iSize;
}
回傳 0;
}
?>
在 64 位元平台上,這個方法對於取得大於 4GB 檔案的大小似乎相當可靠。
<?php
$a = fopen($filename, 'r');
fseek($a, 0, SEEK_END);
$filesize = ftell($a);
fclose($a);
?>
這是取得遠端檔案大小的最佳方法(我目前找到的)。請注意,HEAD 請求不會取得請求的實際內容,它們只會擷取標頭。因此,對 100MB 資源發出 HEAD 請求所需的時間與對 1KB 資源發出 HEAD 請求所需的時間相同。
<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 如果檔案會重新導向 (就像我們這裡使用的 PHP 範例一樣),則為必要
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
echo 'cURL 失敗';
exit;
}
$contentLength = '未知';
$status = '未知';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
$status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo 'HTTP 狀態:' . $status . "\n";
echo '內容長度:' . $contentLength;
?>
結果
HTTP 狀態:302
內容長度:8808759
這是在 32 位元和 64 位元平台上取得大於 2GB 檔案大小的快速可靠方法。
<?php
/**
* 取得檔案大小,不受平台和架構影響。
* 此函式支援 32 位元和 64 位元架構,並適用於大於 2 GB 的檔案
* 返回值類型取決於平台/架構:(float) 當 PHP_INT_SIZE < 8 時,否則為 (int)
* @param resource $fp
* @return mixed (int|float) 成功時返回檔案大小,錯誤時返回 (bool) FALSE
*/
function my_filesize($fp) {
$return = false;
if (is_resource($fp)) {
if (PHP_INT_SIZE < 8) {
// 32 位元
if (0 === fseek($fp, 0, SEEK_END)) {
$return = 0.0;
$step = 0x7FFFFFFF;
while ($step > 0) {
if (0 === fseek($fp, - $step, SEEK_CUR)) {
$return += floatval($step);
} else {
$step >>= 1;
}
}
}
} elseif (0 === fseek($fp, 0, SEEK_END)) {
// 64 位元
$return = ftell($fp);
}
}
return $return;
}
?>
關於前一篇貼文的一些注意事項和修改。
根據 RFC,當使用 HTTP/1.1 時,您的請求(GET、POST 或 HEAD)必須包含 Host 標頭字串,這與 HTTP/1.0 相反,HTTP/1.0 並不需要 Host 標頭。 但無法確定遠端伺服器將如何處理請求,因此您可以隨時添加 Host 標頭(對於 HTTP/1.0 來說,這不會是錯誤)。
Host 值「必須」是主機名稱(不是 CNAME 也不是 IP 位址)。
此函式會擷取包含 Location 標頭的回應,並遞迴地向我們被重新導向的主機發送 HEAD 請求,直到收到最終回應。
(當您從 PHP 腳本或使用 Apache mod_rewrite 的一些雜湊連結下載某些內容時,您經常會遇到這種重新導向。幾乎所有下載管理器都能正確處理 302 重新導向,所以這段程式碼也能做到這一點(透過 302 重新導向遞迴執行)。)
[$counter302] 指定如果遇到重新導向,您允許此函式跳轉多少次。如果超過初始限制(預設為 5),它會返回 0(應根據您的目的修改)。0
ReadHeader() 函式列於前一篇貼文中
(參數說明也放在那裡)。
<?php
function remote_filesize_thru( $ipAddress, $url, $counter302 = 5 )
{
$socket = fsockopen( "10.233.225.2", 8080 );
if( !$socket )
{
// failed to open TCP socket connection
// do something sensible here besides exit();
echo "<br>failed to open socket for [$ipAddress]";
exit();
}
// just send HEAD request to server
$head = "HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n";
// you may use HTTP/1.1 instead, then your request head string _must_ contain "Host: " header
fwrite( $socket, $head );
// read the response header
$header = ReadHeader( $socket );
if( !$header )
{
// handle empty response here the way you need...
Header( "HTTP/1.1 404 Not Found" );
exit();
}
fclose( $socket );
// check for "Location" header
$locationMarker = "Location: ";
$pos = strpos( $header, $locationMarker );
if( $pos > 0 )
{
$counter302--;
if( $counter302 < 0 )
{
// redirect limit (5 by default) expired -- return some warning or do something sensible here
echo "warning: too long redirection sequence";
return 0;
}
// Location is present -- we should determine target host and move there, like any downloading masters do...
// no need to use regex here
$end = strpos( $header, "\n", $pos );
$location = trim( substr( $header, $pos + strlen( $locationMarker ), $end - $pos - strlen( $locationMarker ) ), "\\r\\n" );
// extract pure host (without "http://")
$host = explode( "/", $location );
$ipa = gethostbyname( $host[2] );
// move to Location
return remote_filesize_thru( $ipa, $location, $counter302 );
}
// try to acquire Content-Length within the response
$regex = '/Content-Length:\s([0-9].+?)\s/';
$count = preg_match($regex, $header, $matches);
// if there was a Content-Length field, its value
// will now be in $matches[1]
if( isset( $matches[1] ) )
$size = $matches[1];
else
$size = 0;
return $size;
}
?>
這是先前 filesize2bytes 的更新版本。
現在回傳類型確實是 int。
<?php
/**
* 將人類可讀的檔案大小(例如 10 MB、200.20 GB)轉換為位元組。
*
* @param string $str
* @return int 結果以位元組為單位
* @author Svetoslav Marinov
* @author http://slavi.biz
*/
function filesize2bytes($str) {
$bytes = 0;
$bytes_array = array(
'B' => 1,
'KB' => 1024,
'MB' => 1024 * 1024,
'GB' => 1024 * 1024 * 1024,
'TB' => 1024 * 1024 * 1024 * 1024,
'PB' => 1024 * 1024 * 1024 * 1024 * 1024,
);
$bytes = floatval($str);
if (preg_match('#([KMGTP]?B)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
$bytes *= $bytes_array[$matches[1]];
}
$bytes = intval(round($bytes, 2));
return $bytes;
}
?>
我計算目錄大小的解決方案
<?php
/**
* 取得目錄大小
* @param string $directory 目錄路徑
* @return int
*/
function dirSize($directory) {
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
$size += $file->getSize();
}
return $size;
}
?>
使用 fseek 真的很慢。這個方法更好也更快。
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$size = trim(exec("for %F in (\"" . $file . "\") do @echo %~zF"));
}
elseif ((PHP_OS == 'Linux') || (PHP_OS == 'FreeBSD') || (PHP_OS == 'Unix') || (PHP_OS == 'SunOS')) {
$size = trim(shell_exec("stat -c%s " . escapeshellarg($file)));
} else {
$size = filesize($file);
}
「注意:由於 PHP 的整數類型是有號數,且許多平台使用 32 位元整數,因此某些檔案系統函式對於大於 2GB 的檔案可能會返回非預期的結果。」
這應該是一個警告而不是注意事項:filesize - 正如其他一些評論所建議的 - 對於必須對大型檔案採取自訂動作的應用程式來說是無用的。