folder.png

File and Folder size in php CI

In this tutorial will learn how to calculate the size of any file or any folder by just sending the path to the function, the function will return the file size in kb you can convert it into any format.

Here is one of the best ways to find a folder size and a file size in php.

Below is the code to find the size of a file in kb

    public function filesize_kb($path)
    {
        $file_size = round((filesize($path) / 1000), 5);
        $file_size = $file_size / 1000;
        return $file_size ;

    } 

In above code filesize() is a pre defined function which returns the number of bytes of a file. We can convert it in any format after that.

This function is used to calculate the size of a folder and all the sub folders inside that.

Below is the code to find the size of a folder in kb

public function folderSize($dir)
  {
    $size = 0;
    foreach (glob(rtrim($dir, ‘/’) . ‘/*’, GLOB_NOSORT) as $each) {
      $size += is_file($each) ? filesize($each) : $this->folderSize($each);
    }

    return $size;
  }

This code will give you the size of a folder with its subfolder also. You have to pass the path of the directory in the function.

Tags: No tags

Leave A Comment

Your email address will not be published. Required fields are marked *