- Как определить размер папки
- disk_total_space
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 9 notes
- Get Folder or Directory size in PHP?
- PHP Function
- Call in Action
- Output
- PHP Function to format size
- IT как стиль жизни
- четверг, 10 октября 2013 г.
- Как узнать размер папки на PHP
- Комментариев нет:
- Отправить комментарий
- Популярные сообщения
Как определить размер папки
Здравствуйте, формучане Пытаюсь определить размер папки скриптом php, но выходит довольно туго. Пробовал 2 способа — рекурсивно спускаться в подкаталоги и суммировать размеры попутных файлов и через системный вызов du. В обоих случаях потерпел фиаско: в случае рекурсии либо не работает $handle = opendir ($path), возвращает null, хотя папка существует. Скорее всего это было связано с правами, выдавать полные права на папку не самая лучшая идея, но даже если их выдать is_file ($nextpath) всегда возвращает false, если убрать это условие, то не определяется размер файла filesize ($nextpath), хотя все права на файл стоят.
В случае exec вообще происходит какая-то магия. Из-под консоли запускаю «du -bcS /home/gs24» работает нормально, расписывает всё, что лежит внутри с размерами + размер всей запрашиваемой папки. Пишу то же самое через exec — получаю всего 2 строчки «Array ( [0] => 4096 /home/gs24 [1] => 4096 total )» ?
Может есть какой-то менее костыльный метод определить размер папки, чтобы не мучиться с правами и магией системных вызовов?
Код, про который идёт речь:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
function getDirectorySize($path) { echo $path."
"; $totalsize = 0; $totalcount = 0; $dircount = 0; if ($handle = opendir ($path)) { echo $path."
"; while (false !== ($file = readdir($handle))) { $nextpath = $path . '/' . $file; echo "$nextpath
"; if ($file != '.' && $file != '..' && !is_link ($nextpath)) { if (is_dir ($nextpath)) { $dircount++; $result = getDirectorySize($nextpath); $totalsize += $result['size']; $totalcount += $result['count']; $dircount += $result['dircount']; } elseif (is_file ($nextpath)) { $totalsize += filesize ($nextpath); $totalcount++; } } } } closedir ($handle); $total['size'] = $totalsize; $total['count'] = $totalcount; $total['dircount'] = $dircount; return $total; }
$path = "/home/gs"; $path .= $id; $com = "du -bcS " . $path; exec($com, $mas); print_r($mas);
disk_total_space
Функция возвращает общий размер в байтах указанного раздела диска или каталога.
Список параметров
Директория файловой системы или раздел диска.
Возвращаемые значения
Возвращает общий размер в байтах в виде числа с плавающей точкой или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования disk_total_space()
// $df содержит общий размер диска «/» в байтах
$ds = disk_total_space ( «/» );
?php
// В Windows:
$ds = disk_total_space ( «C:» );
$ds = disk_total_space ( «D:» );
?>
Примечания
Замечание: Эта функция неприменима для работы с удалёнными файлами, поскольку файл должен быть доступен через файловую систему сервера.
Смотрите также
User Contributed Notes 9 notes
// Wrong
$exp = floor ( log ( $bytes ) / log ( 1024 ));
//Correct
$exp = $bytes ? floor ( log ( $bytes ) / log ( 1024 )) : 0 ;
For a non-looping way to add symbols to a number of bytes:
function getSymbolByQuantity ( $bytes ) $symbols = array( ‘B’ , ‘KiB’ , ‘MiB’ , ‘GiB’ , ‘TiB’ , ‘PiB’ , ‘EiB’ , ‘ZiB’ , ‘YiB’ );
$exp = floor ( log ( $bytes )/ log ( 1024 ));
return sprintf ( ‘%.2f ‘ . $symbol [ $exp ], ( $bytes / pow ( 1024 , floor ( $exp ))));
>
To find the total size of a file/directory you have to differ two situations:
(on Linux/Unix based systems only!?)
you are interested:
1) in the total size of the files in the dir/subdirs
2) what place on the disk your dir/subdirs/files uses
— 1) and 2) normaly differs, depending on the size of the inodes
— mostly 2) is greater than 1) (in the order of any kB)
— filesize($file) gives 1)
— «du -ab $file» gives 2)
so you have to choose your situation!
on my server I have no rights to use «exec du» in the case of 2), so I use:
$s = stat($file);
$size = $s[11]*$s[12]/8);
whitch is counting the inodes [12] times the size of them in Bits [11]
hopes this helps to count the used disk place in a right way. 🙂
function roundsize($size) <
$i=0;
$iec = array(«B», «Kb», «Mb», «Gb», «Tb»);
while (($size/1024)>1) <
$size=$size/1024;
$i++;>
return(round($size,1).» «.$iec[$i]);>
Something that might go well with this function is the ability to list available disks. On Windows, here’s the relevant code:
/**
* Finds a list of disk drives on the server.
* @return array The array velues are the existing disks.
*/
function get_disks () <
if( php_uname ( ‘s’ )== ‘Windows NT’ ) <
// windows
$disks =` fsutil fsinfo drives `;
$disks = str_word_count ( $disks , 1 );
if( $disks [ 0 ]!= ‘Drives’ )return » ;
unset( $disks [ 0 ]);
foreach( $disks as $key => $disk ) $disks [ $key ]= $disk . ‘:\\’ ;
return $disks ;
>else <
// unix
$data =` mount `;
$data = explode ( ‘ ‘ , $data );
$disks =array();
foreach( $data as $token )if( substr ( $token , 0 , 5 )== ‘/dev/’ ) $disks []= $token ;
return $disks ;
>
>
?>
EXAMPLE OF USE:
EXAMPLE RESULT:
Array
(
[1] => A:\
[2] => C:\
[3] => D:\
[4] => E:\
[5] => F:\
[6] => G:\
[7] => H:\
[8] => I:\
[9] => M:\
[10] => X:\
[11] => Z:\
)
Warning: This also finds empty disk drives (eg; CD or SMD drives or the more common floppy drive).
Warning2: If you want to find space usage using the info from my function, prepend the disk function with the «@», eg:
//This is a more readable way of viewing the returned float
// $Bytes contains the total number of bytes on «/»
$Bytes = disk_total_space ( «/» );
function dataSize ( $Bytes )
$Type =array( «» , «kilo» , «mega» , «giga» , «tera» );
$counter = 0 ;
while( $Bytes >= 1024 )
$Bytes /= 1024 ;
$counter ++;
>
return( «» . $Bytes . » » . $Type [ $counter ]. «bytes» );
>
?>
Very simple function that convert bytes to kilobytes, megabytes .
return sprintf(«%0.2f Gb», $number/1024/1024/1024);
PHP 6 has already come to the market but still there are no standard function that can help retrieve directory size as it has to calculate disk space such as disk_total_space. Although we can use system level call such as exec() and system(), it is too risky to enable these function. So we look for an alternate method so as to calculate directory size.
Sol: retrieving directory size using php
function get_dir_size ( $dir_name ) $dir_size = 0 ;
if ( is_dir ( $dir_name )) if ( $dh = opendir ( $dir_name )) while (( $file = readdir ( $dh )) !== false ) if( $file != ” . ” && $file != “ .. ” ) if( is_file ( $dir_name . ” / ” . $file )) $dir_size += filesize ( $dir_name . ” / ” . $file );
>
/* check for any new directory inside this directory */
if( is_dir ( $dir_name . ” / ” . $file )) $dir_size += get_dir_size ( $dir_name . ” / ” . $file );
>
>
>
>
>
closedir ( $dh );
return $dir_size ;
>
$dir_name = “directory name here” ;
/* 1048576 bytes == 1MB */
$total_size = round (( get_dir_size ( $dir_name ) / 1048576 ), 2 ) ;
print “Directory $dir_name size : $total_size MB” ;
?>
Depending upon the size format you want to achieve, divide directory size by 1024 or 1024 * 1024 or 1024 * 1024 * 1024 for KB or MB or GB respectively.
Get Folder or Directory size in PHP?
In PHP we have an inbuilt function called filesize() to get the size of any file, but what about a directory/ folder. A folder can content many files and sub folders in it. So lets write down a simple PHP function to calculate the folder size.
PHP Function
function folderSize($dir)< $count_size = 0; $count = 0; $dir_array = scandir($dir); foreach($dir_array as $key=>$filename)< if($filename!=".." && $filename!=".")< if(is_dir($dir."/".$filename))< $new_foldersize = foldersize($dir."/".$filename); $count_size = $count_size+ $new_foldersize; >else if(is_file($dir."/".$filename)) < $count_size = $count_size + filesize($dir."/".$filename); $count++; >> > return $count_size; >
Call in Action
Output
The above function will return the folder size in bytes. So we need to write another function which will convert the bytes to Kilobyte, Megabyte, Gigabyte, Terabyte etc.
PHP Function to format size
function sizeFormat($bytes)< $kb = 1024; $mb = $kb * 1024; $gb = $mb * 1024; $tb = $gb * 1024; if (($bytes >= 0) && ($bytes < $kb)) < return $bytes . ' B'; >elseif (($bytes >= $kb) && ($bytes < $mb)) < return ceil($bytes / $kb) . ' KB'; >elseif (($bytes >= $mb) && ($bytes < $gb)) < return ceil($bytes / $mb) . ' MB'; >elseif (($bytes >= $gb) && ($bytes < $tb)) < return ceil($bytes / $gb) . ' GB'; >elseif ($bytes >= $tb) < return ceil($bytes / $tb) . ' TB'; >else < return $bytes . ' B'; >>
IT как стиль жизни
Блог посвящен IT, но при этом так же охватывает как и около компьютерные темы, так и совершенно не относящиеся к айти вещи.
четверг, 10 октября 2013 г.
Как узнать размер папки на PHP
Для того что бы узнать размер файла есть функция filesize(), а вот для папок нужно писать свою функцию с обходом внутренних папок и подсчетом размера всех файлов, что находятся внутри.
Комментариев нет:
Отправить комментарий
Популярные сообщения
Возникла у меня тут недавно задача: Нужно было запускать музыку в зале в 8 утра, а гасить в 20:00 вечера. Первоначально это делалось вруч.
Не давно наткнулся на интересные ссылки на хабре, по поводу планирования. Думаю многим будет интересно. ссылка раз, ссылка два
Пожалуй каждый верстальщик, либо человек так или иначе делающий сайты или как-то с этим связанный встречается с задачей прижать футер или .
Эххх, случайно вспомнил про одну старенькую 2д игрушку, в которую рубился на отцовом ноуте, который он приносил с работы на выходные и тут к.
Не могу не поделиться весьма интересной ссылкой на целую библиотеку различных закладок по теме ИБ Линк Ссылка взята из одного из последн.
При загрузке звук есть все время, даже если его отключить, что раздражает, особенно ночью или утром, когда нужно тихо включить компьютер не.
Появилась задача: есть папка, в ней куча под-папок, в них соответственно огромное множество различных файлов (pdf, doc, jpeg), необходимо со.
Привет %username%! Сегодня мы разберем утилиту dnsdict6. Как ей пользоваться, какие у нее ключи etc. И так, поехали.