使用php列出目录中的所有文件夹子文件夹和文件

请给我一个使用php列出目录中所有文件夹,子文件夹,文件的解决方案。 我的文件夹结构是这样的:

Main Dir
 Dir1
  SubDir1
   File1
   File2
  SubDir2
   File3
   File4
 Dir2
  SubDir3
   File5
   File6
  SubDir4
   File7
   File8

我想获取每个文件夹中所有文件的列表。

php中有任何shell脚本命令吗?

Warrior asked 2019-11-15T22:58:28Z
17个解决方案
143 votes
function listFolderFiles($dir){
    $ffs = scandir($dir);

    unset($ffs[array_search('.', $ffs, true)]);
    unset($ffs[array_search('..', $ffs, true)]);

    // prevent empty ordered elements
    if (count($ffs) < 1)
        return;

    echo '<ol>';
    foreach($ffs as $ff){
        echo '<li>'.$ff;
        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
        echo '</li>';
    }
    echo '</ol>';
}

listFolderFiles('Main Dir');
Shef answered 2019-11-15T22:58:32Z
15 votes

此代码在树视图中按排序顺序列出了所有目录和文件。 这是一个站点地图生成器,具有指向所有站点资源的超链接。 完整的网页资源在这里。 您需要从最后开始在第9行更改路径。

<?php
$pathLen = 0;

function prePad($level)
{
  $ss = "";

  for ($ii = 0;  $ii < $level;  $ii++)
  {
    $ss = $ss . "|&nbsp;&nbsp;";
  }

  return $ss;
}

function myScanDir($dir, $level, $rootLen)
{
  global $pathLen;

  if ($handle = opendir($dir)) {

    $allFiles = array();

    while (false !== ($entry = readdir($handle))) {
      if ($entry != "." && $entry != "..") {
        if (is_dir($dir . "/" . $entry))
        {
          $allFiles[] = "D: " . $dir . "/" . $entry;
        }
        else
        {
          $allFiles[] = "F: " . $dir . "/" . $entry;
        }
      }
    }
    closedir($handle);

    natsort($allFiles);

    foreach($allFiles as $value)
    {
      $displayName = substr($value, $rootLen + 4);
      $fileName    = substr($value, 3);
      $linkName    = str_replace(" ", "%20", substr($value, $pathLen + 3));
      if (is_dir($fileName)) {
        echo prePad($level) . $linkName . "<br>\n";
        myScanDir($fileName, $level + 1, strlen($fileName));
      } else {
        echo prePad($level) . "<a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a><br>\n";
      }
    }
  }
}

?><!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Site Map</title>
</head>

<body>
<h1>Site Map</h1>
<p style="font-family:'Courier New', Courier, monospace; font-size:small;">
<?php
  $root = '/home/someuser/www/website.com/public';

  $pathLen = strlen($root);

  myScanDir($root, 0, strlen($root)); ?>
</p>
</body>

</html>
nbauers answered 2019-11-15T22:58:56Z
11 votes

显示文件夹结构的一种非常简单的方法是使用RecursiveTreeIterator::setPrefixPart类(PHP 5> = 5.3.0,PHP 7)并生成ASCII图形树。

$it = new RecursiveTreeIterator(new RecursiveDirectoryIterator("/path/to/dir", RecursiveDirectoryIterator::SKIP_DOTS));
foreach($it as $path) {
  echo $path."<br>";
}

[http://php.net/manual/zh/class.recursivetreeiterator.php]

通过使用RecursiveTreeIterator::setPrefixPart(例如$it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "|");)更改前缀,还可以控制树的ASCII表示形式

jim_kastrin answered 2019-11-15T22:59:33Z
10 votes

如果您想使用directoryIterator

以下功能是26She21781781508670464的@Shef答案的重新实现

function listFolderFiles($dir)
{
    echo '<ol>';
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            echo '<li>' . $fileInfo->getFilename();
            if ($fileInfo->isDir()) {
                listFolderFiles($fileInfo->getPathname());
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
listFolderFiles('Main Dir');
WonderLand answered 2019-11-15T23:00:03Z
4 votes

我真的很喜欢SPL库,它们提供了迭代器,包括RecursiveDirectoryIterator。

Wesley van Opdorp answered 2019-11-15T23:00:27Z
2 votes

看一下glob()或递归目录迭代器。

pritaeas answered 2019-11-15T23:00:51Z
2 votes

scandir() [http://php.net/manual/zh/function.scandir.php]

Rijk answered 2019-11-15T23:01:15Z
2 votes

它将用于使菜单栏成为目录格式

$pathLen = 0;

function prePad($level)
{
  $ss = "";

  for ($ii = 0;  $ii < $level;  $ii++)
  {
      $ss = $ss . "|&nbsp;&nbsp;";
    }

    return $ss;
  }

  function myScanDir($dir, $level, $rootLen)
  {
    global $pathLen;

    if ($handle = opendir($dir)) {

      $allFiles = array();

      while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
          if (is_dir($dir . "/" . $entry))
          {
            $allFiles[] = "D: " . $dir . "/" . $entry;
          }
          else
          {
            $allFiles[] = "F: " . $dir . "/" . $entry;
          }
        }
      }
      closedir($handle);

      natsort($allFiles);

      foreach($allFiles as $value)
      {
        $displayName = substr($value, $rootLen + 4);
        $fileName    = substr($value, 3);
        $linkName    = str_replace(" ", " ", substr($value, $pathLen + 3));


        if (is_dir($fileName))
         {
               echo "<li ><a class='dropdown'><span>" . $displayName . "                    </span></a><ul>";

          myScanDir($fileName, $level + 1, strlen($fileName));
            echo "</ul></li>";
  } 
        else {
      $newstring = substr($displayName, -3);  
      if($newstring == "PDF" || $newstring == "pdf" )

          echo "<li ><a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a></li>";

        }
  $t;
        if($level != 0)
        {
          if($level < $t)
          {
        $r = int($t) - int($level);
        for($i=0;$i<$r;$i++)
        {
            echo "</ul></li>";
        }
          } 
        }
              $t = $level;
      }
          }

        }
        ?>

                                        <li style="color: #ffffff">

                                                <?php                                                   
   //  ListFolder('D:\PDF');
     $root = 'D:\PDF';
   $pathLen = strlen($root);

    myScanDir($root, 0, strlen($root)); 
     ?>


                                        </li>
Venkatesh Parihar answered 2019-11-15T23:01:39Z
1 votes

如果您正在寻找列出解决方案的递归目录,并将它们排列在多维数组中。 使用以下代码:

<?php
/**
 * Function for recursive directory file list search as an array.
 *
 * @param mixed $dir Main Directory Path.
 *
 * @return array
 */
function listFolderFiles($dir)
{
    $fileInfo     = scandir($dir);
    $allFileLists = [];

    foreach ($fileInfo as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
                $allFileLists[$folder] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
            } else {
                $allFileLists[$folder] = $folder;
            }
        }
    }

    return $allFileLists;
}//end listFolderFiles()


$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'

?>
Faisal answered 2019-11-15T23:02:03Z
1 votes

这是一个具有scandirarray_filter的简单函数来完成这项工作。 过滤  使用正则表达式所需的文件。 我删除了. ..和诸如.htaccess之类的隐藏文件,还可以使用<ul>和颜色来自定义输出,还可以自定义错误以防万一没有扫描或空目录!

function getAllContentOfLocation($loc)
{   
    $scandir = scandir($loc);

    $scandir = array_filter($scandir, function($element){

        return !preg_match('/^\./', $element);

    });

    if(empty($scandir)) echo '<li style="color:red">Empty Dir</li>';

    foreach($scandir as $file){

        $baseLink = $loc . DIRECTORY_SEPARATOR . $file;

        echo '<ol>';
        if(is_dir($baseLink))
        {
            echo '<li style="font-weight:bold;color:blue">'.$file.'</li>';
            getAllContentOfLocation($baseLink);

        }else{
            echo '<li>'.$file.'</li>';
        }
        echo '</ol>';
    }
}
//Call function and set location that you want to scan 
getAllContentOfLocation('../app');
lotfio answered 2019-11-15T23:02:30Z
1 votes
function GetDir($dir) {
    if (is_dir($dir)) {
        if ($kami = opendir($dir)) {
            while ($file = readdir($kami)) {
                if ($file != '.' && $file != '..') {
                    if (is_dir($dir . $file)) {
                        echo $dir . $file;
                        // since it is a directory we recurse it.
                        GetDir($dir . $file . '/');
                    } else {
                        echo $dir . $file;
                    }
                }
            }
        }
        closedir($kami);
    }
}
kamran Sheikh answered 2019-11-15T23:02:49Z
0 votes

您也可以尝试以下操作:

<?php
function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}

$directory_list = listdirs('xampp');
print_r($directory_list);
?>
Neha Singh answered 2019-11-15T23:03:09Z
0 votes
define ('PATH', $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']));
$dir = new DirectoryIterator(PATH);
echo '<ul>';
foreach ($dir as $fileinfo)
{   
    if (!$fileinfo->isDot()) {
       echo '<li><a href="'.$fileinfo->getFilename().'" target="_blank">'.$fileinfo->getFilename().'</a></li>'; 

       echo '</li>';
    }
}
echo '</ul>';
Gaurang P answered 2019-11-15T23:03:28Z
0 votes

演出晚了,但要以公认的答案为基础...

如果您希望将所有文件和目录作为数组存储(可以使用javascript中的JSON.stringify进行漂亮的装饰),则可以将函数修改为:

function listFolderFiles($dir) { 
    $arr = array();
    $ffs = scandir($dir);

    foreach($ffs as $ff) {
        if($ff != '.' && $ff != '..') {
            $arr[$ff] = array();
            if(is_dir($dir.'/'.$ff)) {
                $arr[$ff] = listFolderFiles($dir.'/'.$ff);
            }
        }
    }

    return $arr;
}

对于新手...

要使用上述JSON.stringify,您的JS / jQuery类似于:

var ajax = $.ajax({
    method: 'POST',
    data: {list_dirs: true}
}).done(function(msg) {
    $('pre').html(
        'FILE LAYOUT<br/>' + 
            JSON.stringify(JSON.parse(msg), null, 4)
    );
});

^这是假设您的HTML中的某个位置有JSON.stringify元素。 任何样式的AJAX都可以,但是我认为大多数人都在使用类似于上面的jQuery的东西。

以及随附的PHP:

if(isset($_POST['list_dirs'])) {
    echo json_encode(listFolderFiles($rootPath));
    exit();
}

您之前已有JSON.stringify

就我而言,我已将JSON.stringify设置为网站的根目录...

$rootPath; 
if(!isset($rootPath)) {
    $rootPath = $_SERVER['DOCUMENT_ROOT'];
}

最终结果是...

|    some_file_1487.smthng    []
|    some_file_8752.smthng    []
|    CSS    
|    |    some_file_3615.smthng    []
|    |    some_file_8151.smthng    []
|    |    some_file_7571.smthng    []
|    |    some_file_5641.smthng    []
|    |    some_file_7305.smthng    []
|    |    some_file_9527.smthng    []
|    
|    IMAGES    
|    |    some_file_4515.smthng    []
|    |    some_file_1335.smthng    []
|    |    some_file_1819.smthng    []
|    |    some_file_9188.smthng    []
|    |    some_file_4760.smthng    []
|    |    some_file_7347.smthng    []
|    
|    JSScripts    
|    |    some_file_6449.smthng    []
|    |    some_file_7864.smthng    []
|    |    some_file_3899.smthng    []
|    |    google-code-prettify    
|    |    |    some_file_2090.smthng    []
|    |    |    some_file_5169.smthng    []
|    |    |    some_file_3426.smthng    []
|    |    |    some_file_8208.smthng    []
|    |    |    some_file_7581.smthng    []
|    |    |    some_file_4618.smthng    []
|    |    
|    |    some_file_3883.smthng    []
|    |    some_file_3713.smthng    []

... and so on...

注意:您的外观将不会完全像这样-我修改了JSON.stringify以显示选项卡(垂直管道),对齐所有键值,删除键引号以及其他一些操作。 如果我要上传答案或引起足够的兴趣,我将通过链接修改此答案。

Birrel answered 2019-11-15T23:04:52Z
0 votes

这篇文章是给Shef(发布正确答案的那个)的。 这是我想向他展示他非常感激他的代码以及我所做的一切的唯一方法。

<!DOCTYPE html>
<head><title>Displays Folder Contents</title></head>
<?php

function frmtFolder($Entity){
 echo '<li style="font-weight:bold;color:black;list-style-type:none">' . $Entity;
}

function frmtFile($dEntry, $fEntry){
echo '<li style="list-style-type:square">' . '<a href="' . $dEntry . '/' . $fEntry . 
'"> ' . $fEntry . ' </a>';
}

function listFolderFiles($dir) {
$ffs = scandir($dir);

unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
unset($ffs[array_search('index.html', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1) {return;}
echo '<ul>';
foreach ($ffs as $ff) {
    if (is_dir($dir . '/' . $ff)) {
     frmtFolder($dir);
    } else {
     frmtFile($dir, $ff);
    }
    if (is_dir($dir . '/' . $ff)) {
        listFolderFiles($dir . '/' . $ff);
    }
    echo '</li>';
}
echo '</ul>';
}
listFolderFiles('Folder_To_List_Here');

我计划将来扩展frmtFile以使用音频和视频标签。

MyKs3D answered 2019-11-15T23:05:24Z
0 votes

先例答案不符合我的需求。

如果要将所有文件和目录放在一个平面数组中,则可以使用此功能(在此处找到):

// Does not support flag GLOB_BRACE        
function glob_recursive($pattern, $flags = 0) {
    $files = glob($pattern, $flags);
    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
    }
    return $files;
}

就我而言:

$paths = glob_recursive(os_path_join($base_path, $current_directory, "*"));

返回我这样的数组:

[
'/home/dir',
'/home/dir/image.png',
'/home/dir/subdir',
'/home/dir/subdir/file.php',
]

您还可以使用动态路径生成:

$paths = glob_recursive(os_path_join($base_path, $directory, "*"));

具有此功能:

function os_path_join(...$parts) {
  return preg_replace('#'.DIRECTORY_SEPARATOR.'+#', DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, array_filter($parts)));
}

如果只需要目录,则可以使用:

$paths = glob_recursive(os_path_join($base_path, $current_directory, "*"));
$subdirs = array_filter($paths, function($path) {
    return is_dir($path);
});
Samuel Dauzon answered 2019-11-15T23:06:27Z
0 votes

我正在寻找与此类似的功能。 我需要将目录作为键,将子目录作为数组和文件,仅将它们作为值放置。
我使用以下代码:

/**
 * Return an array of files found within a specified directory.
 * @param  string $dir   A valid directory. If a path, with a file at the end,
 *                       is passed, then the file is trimmed from the directory.
 * @param  string $regex Optional. If passed, all file names will be checked
 *                       against the expression, and only those that match will
 *                       be returned.
 *                       A RegEx can be just a string, where a '/' will be
 *                       prefixed and a '/i' will be suffixed. Alternatively,
 *                       a string could be a valid RegEx string.
 * @return array         An array of all files from that directory. If regex is
 *                       set, then this will be an array of any matching files.
 */
function get_files_in_dir(string $dir, $regex = null)
{
    $dir = is_dir($dir) ? $dir : dirname($dir);
    // A RegEx to check whether a RegEx is a valid RegEx :D
    $pass = preg_match("/^([^\\\\a-z ]).+([^\\\\a-z ])[a-z]*$/i", $regex, $matches);

    // Any non-regex string will be caught here.
    if (isset($regex) && !$pass) {
        //$regex = '/'.addslashes($regex).'/i';
        $regex = "/$regex/i";
    }

    // A valid regex delimiter with different delimiters will be caught here.
    if (!empty($matches) && $matches[1] !== $matches[2]) {
        $regex .= $matches[1] . 'i'; // Append first delimiter and i flag
    }

    try {
        $files = scandir($dir);
    } catch (Exception $ex) {
        $files = ['.', '..'];
    }
    $files = array_slice($files, 2); // Remove '.' and '..'
    $files = array_reduce($files, function($carry, $item) use ($regex) {
        if ((!empty($regex) && preg_match($regex, $item)) || empty($regex)) {
            array_push($carry, $item);
        }

        return $carry;
    }, []);

    return $files;
}

function str_finish($value, $cap)
{
    $quoted = preg_quote($cap, '/');

    return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
}

function get_directory_tree($dir)
{
    $fs = get_files_in_dir($dir);
    $files = array();

    foreach ($fs as $k => $f) {
        if (is_dir(str_finish($dir, '/').$f)) {
            $fs[$f] = get_directory_tree(str_finish($dir, '/').$f);
        } else {
            $files[] = $f;
        }
        unset($fs[$k]);

    }

    $fs = array_merge($fs, $files);

    return $fs;
}

有很多需要考虑的地方。

创建了第一个函数get_directory_tree,以便我可以基于正则表达式获取目录中的所有文件和文件夹。 我在这里使用它是因为它具有一些错误检查功能,以确保将目录转换为数组。

接下来,我们有一个简单的函数,如果在字符串末尾没有正斜杠,它只会添加一个正斜杠。

最后,我们具有2615928728953816016064函数,该函数将遍历所有文件夹和子文件夹,并创建一个关联数组,其中文件夹名称为键,文件为值(除非文件夹具有子文件夹)。

JustCarty answered 2019-11-15T23:07:26Z
translate from https://stackoverflow.com:/questions/7121479/listing-all-the-folders-subfolders-and-files-in-a-directory-using-php