Hi,
I was looking for the best and fastest way to read the size of a directory. I found a lot of pure php functions which are very slow. I also found some optimized ways depending on the OS. I put all of them together where first the OS dependent versions are used and then the php one as backup.
On my local system the windows version was 18 times faster than the php version.
I have tested this on a couple of systems which where all using the optimized version. So feel free to use this methods.
You can download the functions here:
http://www.tinywebgallery.com/dl.php?file=getFoldersize
Below you find the (unfortunately) unformatted code.
Have fun using it ;),
Michael
/** * Optimized way to the the size of a directoy. * * First the windows or Unix way is tried. If this fails * the php internal stuff is used. * * if you select legacy = false only the pure php * version is used. */ function getFoldersize($path, $legacy = true) { $size = -1; if ($legacy) { if (substr(@php_uname(), 0, 7) == "Windows"){ // we have to make the path absolute ! $path_ab = realpath($path); $obj = new COM ( 'scripting.filesystemobject' ); if ( is_object ( $obj ) ) { $ref = $obj->getfolder ( $path_ab ); $size = $ref->size; $obj = null; } } else { // hopefully unix - du has to be in the path. If it is not you have to adjust the path. $io = popen ( 'du -sb ' . $path, 'r' ); $usize = trim(fgets ( $io, 4096)); $split = preg_split('/s+/', $usize); $usize = $split[0]; pclose ( $io ); if (is_numeric($usize)) { $size = $usize; } } } // backup if both ways fail. It is ~ 18 times slower (tested on windows) than one of the solutions above. if ($size == -1) { $size = foldersize($path); } return $size; } /** * The basic php way to go through all directories and adding the file sizes. */ function foldersize($p) { $size = 0; $fs = scandir($p); foreach($fs as $f) { if (is_dir(rtrim($p, '/') . '/' . $f)) { if ($f!='.' && $f!='..') { $size += foldersize(rtrim($p, '/') . '/' . $f); } } else { $size += filesize(rtrim($p, '/') . '/' . $f); } } return $size; }