使用PHP获取目录中所有文件的名称

Dex*_*erW 82 php directory filenames file

出于某种原因,我使用以下代码持续获得文件名为'1':

if (is_dir($log_directory))
{
    if ($handle = opendir($log_directory))
    {
        while($file = readdir($handle) !== FALSE)
        {
            $results_array[] = $file;
        }
        closedir($handle);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我回显$ results_array中的每个元素时,我得到一堆'1',而不是文件的名称.如何获取文件的名称?

Tat*_*nen 160

不要打扰open/readdir glob而是使用:

foreach(glob($log_directory.'/*.*') as $file) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 因为问题需要文件,你可能希望在该glob周围包装一个`array_filter(...,'is_file')`. (24认同)
  • 并非所有文件名都具有`*.*`形式:只需使用`*`代替. (22认同)
  • 是的,这个答案不是很强大.文件不需要有扩展名,目录可以命名为"something.something".最好使用`array_filter`和`glob($ log_directory.'/*')`. (3认同)

Ili*_*ija 46

SPL风格:

foreach (new DirectoryIterator(__DIR__) as $file) {
  if ($file->isFile()) {
      print $file->getFilename() . "\n";
  }
}
Run Code Online (Sandbox Code Playgroud)

检查DirectoryIteratorSplFileInfo类,以获取可以使用的可用方法列表.


Mik*_*ore 18

你需要$file = readdir($handle)用括号括起来.

干得好:

$log_directory = 'your_dir_name_here';

$results_array = array();

if (is_dir($log_directory))
{
        if ($handle = opendir($log_directory))
        {
                //Notice the parentheses I added:
                while(($file = readdir($handle)) !== FALSE)
                {
                        $results_array[] = $file;
                }
                closedir($handle);
        }
}

//Output findings
foreach($results_array as $value)
{
    echo $value . '<br />';
}
Run Code Online (Sandbox Code Playgroud)


Fle*_*ore 14

只是用glob('*').这是文档


Ali*_*web 12

由于公认的答案有两个重要的缺陷,我正在为那些正在寻找正确答案的新来者发布改进的答案:

foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
    // Do something with $file
}
Run Code Online (Sandbox Code Playgroud)
  1. 过滤globe函数结果is_file是必要的,因为它也可能返回一些目录.
  2. 并非所有文件都有.自己的名字,所以*/*模式一般很糟糕.


小智 7

我有更小的代码:

$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
    echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}
Run Code Online (Sandbox Code Playgroud)


The*_*sor 7

在某些操作系统上,您会获得. ...DS_Store,那么我们无法使用它们,因此我们将它们隐藏起来。

首先开始使用获取有关文件的所有信息 scandir()

// Folder where you want to get all files names from
$dir = "uploads/";

/* Hide this */
$hideName = array('.','..','.DS_Store');    

// Sort in ascending order - this is default
$files = scandir($dir);
/* While this to there no more files are */
foreach($files as $filename) {
    if(!in_array($filename, $hideName)){
       /* echo the name of the files */
       echo "$filename<br>";
    }
}
Run Code Online (Sandbox Code Playgroud)