fteinz fteinz - 9 months ago 40
PHP Question

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

I searching for a way to get a Array of the Files and Folders inside a Folder with the size and the extension like:

$files = array(
array("foo","txt",18), # this is foo.txt with 18 bytes
array("bar","img",513), # this is bar.ing with 513 bytes
array("baz","",345), # this is a Folder with 345 bytes inside

How to solve this? I have tried something like:

$path = /user";
$files = array_diff(scandir($path), array('.', '..'));

Answer Source

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[] = [



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;