如何从文件夹内部获取文件大小和扩展名到数组

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

我正在寻找一种方法来获取文件夹中的文件和文件夹数组,其大小和扩展名如下:

$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
);

如何解决?我试过类似的东西:

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

尝试这样的事情

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

 foreach($filepath as $k=>$v) {
   $files[] =$v;
   $files[] = filesize($v);
   $files[] = pathinfo($v, PATHINFO_EXTENSION);
}

您可以执行以下操作来获取目录中每个文件的数据。

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

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

}

print_r($fileinfo);

请记住,目录只是指向文件列表的指针,因此如果您还想包括该目录的大小,则可以使用递归函数,通过 $file->isDir() 检查在计算尺寸之前。

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;
}

Filepath and filesize 将为您提供所需的信息。

试试这个:

<?php
    $path = __DIR__;
    $files_info = array();
    $i = 0;

    if(is_dir($path)){
        $dh = opendir($path);
        while(($file = readdir($dh)) != false){
            $pathinfo = pathinfo($file);

            if($pathinfo["filename"] != '' and $pathinfo["filename"] != '.'){
                $files_info[$i] = array($pathinfo["filename"], $pathinfo["extension"], filesize($file));
                $i++;
            }
        }

        var_dump($files_info);
    }
?>