Home >Backend Development >PHP Tutorial >How to Efficiently Calculate a Directory\'s Size in PHP?

How to Efficiently Calculate a Directory\'s Size in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 13:41:20788browse

How to Efficiently Calculate a Directory's Size in PHP?

How to Determine Directory Size Using PHP

Calculating the size of a directory, including its subdirectories, can be an important task for managing file storage and performance. This article demonstrates how to achieve this in PHP using an optimized approach.

Existing Method

The provided PHP code snippet calculates the size of a directory as follows:

function foldersize($path) {
  $total_size = 0;
  $files = scandir($path);

  foreach($files as $t) {
    if (is_dir(rtrim($path, '/') . '/' . $t)) {
      if ($t<>"." &amp;&amp; $t<>"..") {
          $size = foldersize(rtrim($path, '/') . '/' . $t);

          $total_size += $size;
      }
    } else {
      $size = filesize(rtrim($path, '/') . '/' . $t);
      $total_size += $size;
    }
  }
  return $total_size;
}

Optimization

The original code exhibited performance issues due to unnecessary recursive function calls and redundant file exists checks. The optimized function below addresses these concerns:

function GetDirectorySize($path){
    $bytestotal = 0;
    $path = realpath($path);
    if($path!==false &amp;&amp; $path!='' &amp;&amp; file_exists($path)){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}

Key enhancements include:

  • Verifying the path using realpath.
  • Checking for pathvalidity and file existence before iteration.
  • Skipping . and .. directories.
  • Using the FilesystemIterator::SKIP_DOTS flag to avoid processing hidden directories and files.

Example Usage

Utilizing the optimized function:

$path = '/var/www/html/myproject';
$directorySize = GetDirectorySize($path);
echo "Size of '$path': " . format_bytes($directorySize);

This code determines the size of the specified directory and displays the result in a human-readable format.

The above is the detailed content of How to Efficiently Calculate a Directory\'s Size in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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