fteinz fteinz - 19 days ago 7
PHP Question

How to get File sizes and extensions fron files inside a Folder in a 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:

<?php
$path = /user";
$files = array_diff(scandir($path), array('.', '..'));
#print_r($files);
?>

Answer

You can do the following:

foreach (new DirectoryIterator('/var/www') as $file) {
    if($file->isDot()) continue; // you can also add "|| $file->isDir()"

    $fileinfo[] = [
        $file->getFilename(),
        $file->getExtension(), // leaves an empty string if it is a directory
        $file->getSize()
    ];

}

print_r($fileinfo);