【问题标题】:How to list files and folder in a dir (PHP) [duplicate]如何列出目录中的文件和文件夹(PHP)[重复]
【发布时间】:2010-10-29 09:15:03
【问题描述】:

您好,我正在尝试使用 php 显示目录中的所有文件和文件夹

例如

目录:系统/信息/

文件夹 - 用户

来自用户的文件 - User1.txt

来自用户的文件 - User2.txt

来自用户的文件 - User3.txt

来自用户的文件 - User4.txt

文件夹 - 玩家

来自玩家的文件 - Player1.txt

来自玩家的文件 - Player2.txt

来自玩家的文件 - Player3.txt

来自玩家的文件 - Player4.txt

请有人带我走正确的街道

谢谢

【问题讨论】:

标签: php


【解决方案1】:

//path to directory to scan
$directory = "../data/team/";

//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");

//print each file name
foreach($texts as $text)
{
    echo $text;
}

【讨论】:

  • 检查文件是否为.txt 的好点。尽管问题不是要求*.txt 文件,但还是要投赞成票。
  • @Korcholis 问题中的示例仅适用于.txt 文件。同样很明显,这也可以通过将 .txt 替换为您想要的任何其他扩展名来工作。
【解决方案2】:

PHP 5 有RecursiveDirectoryIterator

手册有一个基本的例子:

<?php

$directory = '/system/infomation/';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) {

    if (!$it->isDot()) {

        echo 'SubPathName: ' . $it->getSubPathName() . "\n";
        echo 'SubPath:     ' . $it->getSubPath() . "\n";
        echo 'Key:         ' . $it->key() . "\n\n";
    }

    $it->next();
}

?>

编辑 -- 这是一个稍微高级一点的例子(只是稍微有点),它产生的输出类似于你想要的(即文件夹名称然后是文件)。

// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
    FilesystemIterator::SKIP_DOTS);

// Flatten the recursive iterator, folders come before their files
$it  = new RecursiveIteratorIterator($dir,
    RecursiveIteratorIterator::SELF_FIRST);

// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);

// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
    if ($fileinfo->isDir()) {
        printf("Folder - %s\n", $fileinfo->getFilename());
    } elseif ($fileinfo->isFile()) {
        printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
    }
}

【讨论】:

  • +1 用于回答明显重复的 CW
  • 您是否有机会使属于该文件夹的所有文件都列在该文件夹名称下?
  • @Gully 是的,使用 basename()dirname()
  • @Gully 查看第二个示例代码 sn-p
  • 使用第二个代码 sn-p 给我一个错误。关于打开文件太多的问题。这是服务器设置问题吗?
【解决方案3】:

你可以使用:

 foreach (new DirectoryIterator("./system/information/") as $fn) {
     print $fn->getFilename();
 }

您必须为每个子目录、Players 和 User 使用两次。

【讨论】:

    【解决方案4】:

    您可以使用目录功能:http://php.net/manual/en/book.dir.php

    来自opendir()函数描述的简单示例:

    <?php
    $dir_path = "/path/to/your/dir";
    
    if (is_dir($dir_path)) {
        if ($dir_handler = opendir($dir_path)) {
            while (($file = readdir($dir_handler)) !== false) {
                echo "filename: $file : filetype: " . filetype($dir_path . $file) . "\n";
            }
            closedir($dir_handler);
        }
    }
    ?>
    

    【讨论】:

      【解决方案5】:

      列出文件夹中的文件 - 1 个解决方案

      <?php 
      // open this directory 
      $myDirectory = opendir(".");
      // get each entry
      while($entryName = readdir($myDirectory)) {
          $dirArray[] = $entryName;
      }
      // close directory
      closedir($myDirectory);
      //  count elements in array
      $indexCount = count($dirArray);
      Print ("$indexCount files<br>\n");
      // sort 'em
      sort($dirArray);
      // print 'em
      print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
      print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");
      // loop through the array of files and print them all
      for($index=0; $index < $indexCount; $index++) {
              if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
              print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
              print("<td>");  print(filetype($dirArray[$index])); print("</td>");
              print("<td>");  print(filesize($dirArray[$index])); print("</td>");
              print("</TR>\n");
          }
      }
      print("</TABLE>\n");
      ?>
      

      2个解决方案

      <?PHP
      # The current directory
      $directory = dir("./");
      
      # If you want to turn on Extension Filter, then uncomment this:
      ### $allowed_ext = array(".sample", ".png", ".jpg", ".jpeg", ".txt", ".doc", ".xls"); 
      
      
      
      
      ## Description of the soft: list_dir_files.php  
      ## Major credits: phpDIRList 2.0 -(c)2005 Ulrich S. Kapp :: Systemberatung ::
      
      $do_link = TRUE; 
      $sort_what = 0; //0- by name; 1 - by size; 2 - by date
      $sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
      
      
      # # #
      function dir_list($dir){ 
          $i=0; 
          $dl = array(); 
          if ($hd = opendir($dir))    { 
              while ($sz = readdir($hd)) {  
                  if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;  
              } 
          closedir($hd); 
          } 
          asort($dl); 
          return $dl; 
      } 
      if ($sort_how == 0) { 
          function compare0($x, $y) {  
              if ( $x[0] == $y[0] ) return 0;  
              else if ( $x[0] < $y[0] ) return -1;  
              else return 1;  
          }  
          function compare1($x, $y) {  
              if ( $x[1] == $y[1] ) return 0;  
              else if ( $x[1] < $y[1] ) return -1;  
              else return 1;  
          }  
          function compare2($x, $y) {  
              if ( $x[2] == $y[2] ) return 0;  
              else if ( $x[2] < $y[2] ) return -1;  
              else return 1;  
          }  
      }else{ 
          function compare0($x, $y) {  
              if ( $x[0] == $y[0] ) return 0;  
              else if ( $x[0] < $y[0] ) return 1;  
              else return -1;  
          }  
          function compare1($x, $y) {  
              if ( $x[1] == $y[1] ) return 0;  
              else if ( $x[1] < $y[1] ) return 1;  
              else return -1;  
          }  
          function compare2($x, $y) {  
              if ( $x[2] == $y[2] ) return 0;  
              else if ( $x[2] < $y[2] ) return 1;  
              else return -1;  
          }  
      
      } 
      
      ################################################## 
      #    We get the information here 
      ################################################## 
      
      $i = 0; 
      while($file=$directory->read()) { 
          $file = strtolower($file);
          $ext = strrchr($file, '.');
          if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
              {
                  // dump 
              }
          else { 
              $temp_info = stat($file); 
              $new_array[$i][0] = $file; 
              $new_array[$i][1] = $temp_info[7]; 
              $new_array[$i][2] = $temp_info[9]; 
              $new_array[$i][3] = date("F d, Y", $new_array[$i][2]); 
              $i = $i + 1; 
              } 
      } 
      $directory->close(); 
      
      ################################################## 
      # We sort the information here 
      ################################################# 
      
      switch ($sort_what) { 
          case 0: 
                  usort($new_array, "compare0"); 
          break; 
          case 1: 
                  usort($new_array, "compare1"); 
          break; 
          case 2: 
                  usort($new_array, "compare2"); 
          break; 
      } 
      
      ############################################################### 
      #    We display the infomation here 
      ############################################################### 
      
      $i2 = count($new_array); 
      $i = 0; 
      echo "<table border=1> 
                      <tr> 
                          <td width=150> File name</td> 
                          <td width=100> File Size</td> 
                          <td width=100>Last Modified</td> 
                      </tr>"; 
      for ($i=0;$i<$i2;$i++) { 
          if (!$do_link) { 
              $line = "<tr><td align=right>" .  
                              $new_array[$i][0] .  
                              "</td><td align=right>" .  
                              number_format(($new_array[$i][1]/1024)) .  
                              "k"; 
              $line = $line  . "</td><td align=right>" . $new_array[$i][3] . "</td></tr>"; 
          }else{ 
              $line = '<tr><td align=right><A HREF="' .   
                              $new_array[$i][0] . '">' .  
                              $new_array[$i][0] .  
                              "</A></td><td align=right>"; 
              $line = $line . number_format(($new_array[$i][1]/1024)) .  
                              "k"  . "</td><td align=right>" .  
                              $new_array[$i][3] . "</td></tr>"; 
          } 
          echo $line; 
      } 
      echo "</table>"; 
      
      
      ?>
      

      【讨论】:

      • 为什么解决方案#1 没有列出除 .php 文件之外的任何文件?
      【解决方案6】:

      使用此功能http://www.codingforums.com/showthread.php?t=71882

      function getDirectory( $path = '.', $level = 0 ){
      
      $ignore = array( 'cgi-bin', '.', '..' ); 
      // Directories to ignore when listing output. Many hosts 
      // will deny PHP access to the cgi-bin. 
      
      $dh = @opendir( $path ); 
      // Open the directory to the handle $dh 
      
      while( false !== ( $file = readdir( $dh ) ) ){ 
      // Loop through the directory 
      
          if( !in_array( $file, $ignore ) ){ 
          // Check that this file is not to be ignored 
      
              $spaces = str_repeat( '&nbsp;', ( $level * 4 ) ); 
              // Just to add spacing to the list, to better 
              // show the directory tree. 
      
              if( is_dir( "$path/$file" ) ){ 
              // Its a directory, so we need to keep reading down... 
      
                  echo "<strong>$spaces $file</strong><br />"; 
                  getDirectory( "$path/$file", ($level+1) ); 
                  // Re-call this same function but on a new directory. 
                  // this is what makes function recursive. 
      
              } else { 
      
                  echo "$spaces $file<br />"; 
                  // Just print out the filename 
      
              } 
      
          } 
      
      } 
      
      closedir( $dh ); 
      // Close the directory handle 
      }
      

      然后像这样调用函数

      getDirectory( "." ); 
      // Get the current directory 
      
      getDirectory( "./files/includes" ); 
      // Get contents of the "files/includes" folder 
      

      【讨论】:

        【解决方案7】:

        使用全局。有全面的指南如何从 dir 打开所有文件: PHP: Using functional programming for listing files and directories

        【讨论】:

          【解决方案8】:
          【解决方案9】:

          我在 www.laughing-buddha.net/php/lib/dirlist/ 中找到了一个函数,它返回一个包含目录内容列表的数组。

          还可以查看 php.net http://es.php.net/manual/es/ref.filesystem.php,您会在其中找到处理 php 文件的其他功能。

          【讨论】:

            【解决方案10】:

            看看building a simple directory browser using php RecursiveDirectoryIterator

            此外,正如您提到的,您还可以查看一些创建文件/文件夹资源管理器的现成库,例如:

            【讨论】:

              【解决方案11】:

              如果你访问路径有问题,也许你需要把这个:

              $root = $_SERVER['DOCUMENT_ROOT'];
              $path = "/cv/"; 
              
              // Open the folder
               $dir_handle = @opendir($root . $path) or die("Unable to open $path");
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-06-08
                • 2011-10-30
                • 1970-01-01
                • 1970-01-01
                • 2014-01-25
                • 1970-01-01
                • 2011-04-19
                相关资源
                最近更新 更多