PHP - Get the Size of a Directory

How to get directory size in PHP

The following are other solutions offered elsewhere:

If on a Windows Host:

<?
$f = 'f:/www/docs';
$obj = new COM ( 'scripting.filesystemobject' );
if ( is_object ( $obj ) )
{
$ref = $obj->getfolder ( $f );
echo 'Directory: ' . $f . ' => Size: ' . $ref->size;
$obj = null;
}
else
{
echo 'can not create object';
}
?>

Else, if on a Linux Host:

<?
$f = './path/directory';
$io = popen ( '/usr/bin/du -sk ' . $f, 'r' );
$size = fgets ( $io, 4096);
$size = substr ( $size, 0, strpos ( $size, "\t" ) );
pclose ( $io );
echo 'Directory: ' . $f . ' => Size: ' . $size;
?>

How to get the directory size in php

Use This it will works for you

<?php
$units = explode(' ', 'B KB MB GB TB PB');
$SIZE_LIMIT = 5368709120; // 5 GB change it to 10 Gb
$disk_used = foldersize("/folder/");

$disk_remaining = $SIZE_LIMIT - $disk_used;

echo("<html><body>");
echo('diskspace used: ' . format_size($disk_used) . '<br>');
echo( 'diskspace left: ' . format_size($disk_remaining) . '<br><hr>');
echo("</body></html>");

function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/'). '/';

foreach($files as $t) {
if ($t<>"." && $t<>"..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
}
else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}

return $total_size;
}

function format_size($size) {
global $units;

$mod = 1024;

for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}

$endIndex = strpos($size, ".")+3;

return substr( $size, 0, $endIndex).' '.$units[$i];
}

?>

Using filesize() to get the total file size of a directory and it's contents

to get directory size : source

function dir_size($directory) {
$size = 0;
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
$size += $file->getSize();
}
return $size;
}

format the return value with following function to get human readable value : source

function format_size($size) {
$mod = 1024;
$units = explode(' ','B KB MB GB TB PB');
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
return round($size, 2) . ' ' . $units[$i];
}

How to get file sizes and extensions from inside a folder to an array

You can do the following to fetch the data for each file in a directory.

foreach (new DirectoryIterator('/var/www') as $file) {
if($file->isDot()) continue;

$fileinfo[] = [
$file->getFilename(),
$file->getExtension(),
$file->getSize()
];

}

print_r($fileinfo);

Keep in mind, that a directory is merely a pointer to a list of files so if you want to include the size of that directory as well, you can use a recursive function, check by doing $file->isDir() before calculating the size.

function getDirContentSize($path){
$size = 0;
foreach (new DirectoryIterator($path) as $file){
if($file->isDot()) continue;
$size += ($file->isDir()) ? getDirContentSize("$path/$file") : $file->getSize();
}

return $size;
}

how to get each file size individually from directory PHP

From here

 $files = scandir('soft');    
foreach($files as $file) {
if (!in_array($file,array(".","..")))
{
echo $file . "<br />";
echo filesize('soft/'.$file) . ' bytes';
}
}

Just need to keep in mind that scandir gets only the filenames in that dir, and not the relative path to it. that's why you need to use 'soft/'.$file and not $file

how to get the size of folders in php?

Try this,

<?
$f = 'D:/WWebserver/Storage/';
$obj = new COM ( 'scripting.filesystemobject' );
if ( is_object ( $obj ) )
{
$ref = $obj->getfolder ( $f );
echo 'Directory: ' . $f . ' => Size: ' . $ref->size;
$obj = null;
}
else
{
echo 'can not create object';
}
?>

referring.
php get directory size

i want get the sum of files size in folder by php

With DirectoryIterator and SplFileInfo

$totalSize = 0;
foreach (new DirectoryIterator('/path/to/dir') as $file) {
if ($file->isFile()) {
$totalSize += $file->getSize();
}
}
echo $totalSize;

and in case you need that including subfolders:

$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/dir')
);

$totalSize = 0;
foreach ($iterator as $file) {
$totalSize += $file->getSize();
}
echo $totalSize;

And you can run $totalSize through the code we gave you to format 6000 to 6k for a more human readable output. You'd have to change all 1000s to 1024 though.

How to calculate entire directory size with FTP access using PHP

If your server supports MLSD command and you have PHP 7.2 or newer, you can use ftp_mlsd function:

function calculate_whole_directory($ftp_conn, $directory)
{
$files = ftp_mlsd($ftp_conn, $directory) or die("Cannot list $directory");
$result = 0;
foreach ($files as $file)
{
if (($file["type"] == "cdir") || ($file["type"] == "pdir"))
{
$size = 0;
}
else if ($file["type"] == "dir")
{
$size = calculate_whole_directory($ftp_conn, $directory."/".$file["name"]);
}
else
{
$size = intval($file["size"]);
}
$result += $size;
}

return $result;
}

If you do not have PHP 7.2, you can try to implement the MLSD command on your own. For a start, see user comment of the ftp_rawlist command:

https://www.php.net/manual/en/function.ftp-rawlist.php#101071


If you cannot use MLSD, you will particularly have problems telling if an entry is a file or folder. While you can use the ftp_size trick, as you do, calling ftp_size for each entry can take ages.

But if you need to work against one specific FTP server only, you can use ftp_rawlist to retrieve a file listing in a platform-specific format and parse that.

The following code assumes a common *nix format.

function calculate_whole_directory($ftp_conn, $directory)
{
$lines = ftp_rawlist($ftp_conn, $directory) or die("Cannot list $directory");
$result = 0;
foreach ($lines as $line)
{
$tokens = preg_split("/\s+/", $line, 9);
$name = $tokens[8];
if ($tokens[0][0] === 'd')
{
$size = calculate_whole_directory($ftp_conn, "$directory/$name");
}
else
{
$size = intval($tokens[4]);
}
$result += $size;
}

return $result;
}

Based on PHP FTP recursive directory listing.


Regarding cron: I'd guess that the cron does not start your script with a correct working directory, so you calculate a size of a non-existing directory.

Use an absolute path here:

$directory = '../public_html/'; 

Though you better add some error checking so that you can see yourself what goes wrong.



Related Topics



Leave a reply



Submit