Home > Backend Development > PHP Tutorial > A php function that counts directory file size, _PHP tutorial

A php function that counts directory file size, _PHP tutorial

WBOY
Release: 2016-07-12 09:02:53
Original
774 people have browsed it

A php function that counts the size of files in a directory.

I just arrived at the company this morning and my boss told me to hurry up and write a small function to count the size of files in a specified directory. I got it. Go ahead and do it, luckily you have a little basic knowledge and you’ll be done in a while, haha. The code is below.

  1. /**
  2. Function to count directory file size
  3. @author xfcode
  4. @link http://www.jbxue.com
  5. */
  6. function dirsize($dir)
  7. {
  8.  @$dh = opendir($dir);
  9. $size = 0;
  10.  while ($file = @readdir($dh))
  11.  {
  12.  if ($file != "." and $file != "..")
  13.  {
  14.   $path = $dir."/".$file;
  15.   if (is_dir($path))
  16.   {
  17.   $size = dirsize($path);
  18.   }  
  19. elseif (is_file($path))
  20.   {
  21.   $size = filesize($path);
  22.   }  
  23.  }  
  24.  }
  25. @closedir($dh);
  26.  return $size;
  27. }
  28. //functionend 
  29. //eg:
  30. $dir_path = "./my_files";
  31. $dir_size = dirsize($dir_path);
  32. $dir_size = $dir_size/1024/1024;
  33. echo $dir_size."MB";
  34. ?>

This function can recursively loop through all files in a directory and calculate the total file size in MB.
The newbie makes a move, and the bosses laugh.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1084385.htmlTechArticleA php function that counts the size of directory files. I just arrived at the company this morning and my boss told me to hurry up and write a small function. Used to count the size of files in a specified directory. Let me go and do it. Fortunately...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template