欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php计算整个目录大小的方法

程序员文章站 2022-06-22 20:43:24
本文实例讲述了php计算整个目录大小的方法。分享给大家供大家参考。具体实现方法如下: /** * calculate the full size of a d...

本文实例讲述了php计算整个目录大小的方法。分享给大家供大家参考。具体实现方法如下:

/**
 * calculate the full size of a directory
 *
 * @author   jonas john
 * @version   0.2
 * @link    http://www.jonasjohn.de/snippets/php/dir-size.htm
 * @param    string  $directorypath  directory path
 */
function calcdirectorysize($directorypath) {
  // i reccomend using a normalize_path function here
  // to make sure $directorypath contains an ending slash
  // (-> http://www.jonasjohn.de/snippets/php/normalize-path.htm)
  // to display a good looking size you can use a readable_filesize
  // function.
  // (-> http://www.jonasjohn.de/snippets/php/readable-filesize.htm)
  $size = 0;
  $dir = opendir($directorypath);
  if (!$dir)
    return -1;
  while (($file = readdir($dir)) !== false) {
    // skip file pointers
    if ($file[0] == '.') continue; 
    // go recursive down, or add the file size
    if (is_dir($directorypath . $file))      
      $size += calcdirectorysize($directorypath . $file . directory_separator);
    else 
      $size += filesize($directorypath . $file);    
  }
  closedir($dir);
  return $size;
}
//使用范例:
$sizeinbytes = calcdirectorysize('data/');

希望本文所述对大家的php程序设计有所帮助。