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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2922954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:09:09  来源:igfitidea点击:

Getting the names of all files in a directory with PHP

phpfiledirectoryfilenames

提问by DexterW

For some reason, I keep getting a '1' for the file names with this code:

出于某种原因,我使用以下代码不断获得文件名的“1”:

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

When I echo each element in $results_array, I get a bunch of '1's, not the name of the file. How do I get the name of the files?

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

回答by Tatu Ulmanen

Don't bother with open/readdir and use globinstead:

不要打扰 open/readdir 并使用glob

foreach(glob($log_directory.'/*.*') as $file) {
    ...
}

回答by Ilija

SPLstyle:

SPL风格:

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

Check DirectoryIteratorand SplFileInfoclasses for the list of available methods that you can use.

检查DirectoryIteratorSplFileInfo类以获取您可以使用的可用方法列表。

回答by Mike Moore

You need to surround $file = readdir($handle)with parentheses.

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

Here you go:

干得好:

$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 />';
}

回答by Fletcher Moore

Just use glob('*'). Here's Documentation

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

回答by Aliweb

As the accepted answer has two important shortfalls, I'm posting the improved answer for those new comers who are looking for a correct answer:

由于接受的答案有两个重要的不足,我将向那些正在寻找正确答案的新人发布改进的答案:

foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
    // Do something with $file
}
  1. Filtering the globefunction results with is_fileis necessary, because it might return some directories as well.
  2. Not all files have a .in their names, so */*pattern sucks in general.
  1. 过滤globe函数结果is_file是必要的,因为它也可能返回一些目录。
  2. 并非所有文件.的名称中都有 a ,因此*/*模式通常很糟糕。

回答by YooRich.com

I have smaller code todo this:

我有更小的代码来做到这一点:

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

回答by TheCrazyProfessor

On some OS you get ...and .DS_Store, Well we can't use them so let's us hide them.

在某些OS你...并且.DS_Store,嗯,我们不能用他们,让我们隐藏它们。

First start get all information about the files, using scandir()

首先开始获取有关文件的所有信息,使用 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>";
    }
}

回答by ircmaxell

It's due to operator precidence. Try changing it to:

这是由于操作员的偏好。尝试将其更改为:

while(($file = readdir($handle)) !== FALSE)
{
    $results_array[] = $file;
}
closedir($handle);

回答by Danijel

glob()and FilesystemIteratorexamples:

glob()FilesystemIterator例子:

/* 
 * glob() examples
 */

// get the array of full paths
$result = glob( 'path/*' );

// get the array of file names
$result = array_map( function( $item ) {
    return basename( $item );
}, glob( 'path/*' ) );


/* 
 * FilesystemIterator examples
 */

// get the array of file names by using FilesystemIterator and array_map()
$result = array_map( function( $item ) {
    // $item: SplFileInfo object
    return $item->getFilename();
}, iterator_to_array( new FilesystemIterator( 'path' ), false ) );

// get the array of file names by using FilesystemIterator and iterator_apply() filter
$it = new FilesystemIterator( 'path' );
iterator_apply( 
    $it, 
    function( $item, &$result ) {
        // $item: FilesystemIterator object that points to current element
        $result[] = (string) $item;
        // The function must return TRUE in order to continue iterating
        return true;
    }, 
    array( $it, &$result )
);

回答by Ad Kahn

You could just try the scandir(Path)function. it is fast and easy to implement

你可以试试这个scandir(Path)功能。它快速且易于实施

Syntax:

句法:

$files = scandir("somePath");

This Function returns a list of file into an Array.

此函数将文件列表返回到数组中。

to view the result, you can try

查看结果,你可以试试

var_dump($files);

Or

或者

foreach($files as $file)
{ 
echo $file."< br>";
}