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

发布于 2024-09-03 09:03:10 字数 343 浏览 2 评论 0原文

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

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

窗影残 2024-09-10 09:03:10

不要打扰 open/readdir 并使用 glob 相反:

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

Don't bother with open/readdir and use glob instead:

foreach(glob($log_directory.'/*.*') as $file) {
    ...
}
不及他 2024-09-10 09:03:10

SPL 样式:

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

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

SPL style:

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

Check DirectoryIterator and SplFileInfo classes for the list of available methods that you can use.

挥剑断情 2024-09-10 09:03:10

由于已接受的答案有两个重要的缺陷,因此我为那些正在寻找正确答案的新人发布了改进的答案:

foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
    // Do something with $file
}
  1. 使用 is_file 过滤 glob 函数结果是必要的,因为它也可能返回一些目录。
  2. 并非所有文件的名称中都包含 .,因此 */* 模式通常很糟糕。

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 glob function results with is_file is necessary, because it might return some directories as well.
  2. Not all files have a . in their names, so */* pattern sucks in general.
甜嗑 2024-09-10 09:03:10

您需要用括号将 $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 />';
}

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

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 />';
}
眼眸里的那抹悲凉 2024-09-10 09:03:10

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

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

遗心遗梦遗幸福 2024-09-10 09:03:10

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

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

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/>";
}
放赐 2024-09-10 09:03:10

在某些操作系统上,您会得到 . ...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>";
    }
}

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

First start get all information about the files, using 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>";
    }
}
玩世 2024-09-10 09:03:10

这是由于操作员的优先级。尝试将其更改为:

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

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

while(($file = readdir($handle)) !== FALSE)
{
    $results_array[] = $file;
}
closedir($handle);
柠北森屋 2024-09-10 09:03:10

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

glob() and FilesystemIterator examples:

/* 
 * 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 )
);
鸩远一方 2024-09-10 09:03:10

您可以尝试使用 scandir(Path) 函数。它实现起来既快速又简单。

语法:

$files = scandir("somePath");

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

要查看结果,您可以尝试

var_dump($files);

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

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

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>";
} 
π浅易 2024-09-10 09:03:10

列出目录和文件的另一种方法是使用此处回答的 RecursiveTreeIteratorhttps://stackoverflow.com/ a/37548504/2032235

关于 PHP 中的 RecursiveIteratorIterator 和迭代器的完整解释可以在这里找到:https://stackoverflow.com/a /12236744/2032235

Another way to list directories and files would be using the RecursiveTreeIterator answered here: https://stackoverflow.com/a/37548504/2032235.

A thorough explanation of RecursiveIteratorIterator and iterators in PHP can be found here: https://stackoverflow.com/a/12236744/2032235

↘人皮目录ツ 2024-09-10 09:03:10

我只是使用这段代码:

<?php
    $directory = "Images";
    echo "<div id='images'><p>$directory ...<p>";
    $Files = glob("Images/S*.jpg");
    foreach ($Files as $file) {
        echo "$file<br>";
    }
    echo "</div>";
?>

I just use this code:

<?php
    $directory = "Images";
    echo "<div id='images'><p>$directory ...<p>";
    $Files = glob("Images/S*.jpg");
    foreach ($Files as $file) {
        echo "$file<br>";
    }
    echo "</div>";
?>
掐死时间 2024-09-10 09:03:10

使用:

if ($handle = opendir("C:\wamp\www\yoursite/download/")) {

    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<b>" . preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry) . "</b>";
        }
    }
    closedir($handle);
}

来源:http: //chandreshrana.blogspot.com/2016/08/how-to-fetch-all-files-name-from-folder.html

Use:

if ($handle = opendir("C:\wamp\www\yoursite/download/")) {

    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<b>" . preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry) . "</b>";
        }
    }
    closedir($handle);
}

Source: http://chandreshrana.blogspot.com/2016/08/how-to-fetch-all-files-name-from-folder.html

遇见了你 2024-09-10 09:03:10

递归代码探索目录中包含的所有文件(“$path”包含目录的路径):

function explore_directory($path)
{
    $scans = scandir($path);

    foreach($scans as $scan)
    {
        $new_path = $path.$scan;

        if(is_dir($new_path))
        {
            $new_path = $new_path."/";
            explore_directory($new_path);
        }
        else // A file
        {
            /*
                  Body of code
            */
        }
    }
}

Recursive code to explore all the file contained in a directory ('$path' contains the path of the directory):

function explore_directory($path)
{
    $scans = scandir($path);

    foreach($scans as $scan)
    {
        $new_path = $path.$scan;

        if(is_dir($new_path))
        {
            $new_path = $new_path."/";
            explore_directory($new_path);
        }
        else // A file
        {
            /*
                  Body of code
            */
        }
    }
}
ゃ懵逼小萝莉 2024-09-10 09:03:10

我为此创建了一些小东西:

function getFiles($path) {
    if (is_dir($path)) {
        $res = array();
        foreach (array_filter(glob($path ."*"), 'is_file') as $file) {
            array_push($res, str_replace($path, "", $file));                
        }
        return $res;
    }
    return false;
}

Little something I created for this:

function getFiles($path) {
    if (is_dir($path)) {
        $res = array();
        foreach (array_filter(glob($path ."*"), 'is_file') as $file) {
            array_push($res, str_replace($path, "", $file));                
        }
        return $res;
    }
    return false;
}
川水往事 2024-09-10 09:03:10

这将列出文件并创建在新窗口中打开的链接。就像常规服务器索引页一样:

<!DOCTYPE html>
<html>
<head>
    <title>Index of Files</title>
</head>
<body>
    <h1>Index of Files</h1>
    <ul>
        <?php
        // Get the current directory
        $dir = '.';
        
        // Open a directory handle
        if ($handle = opendir($dir)) {
            // Loop through each file in the directory
            while (false !== ($file = readdir($handle))) {
                // Exclude directories and the current/parent directory entries
                if ($file != "." && $file != ".." && !is_dir($file)) {
                    // Generate the link to the file
                    $link = $dir . '/' . $file;
                    
                    // Output the link
                    echo '<li><a href="' . $link . '" target="_blank">' . $file . '</a></li>';
                }
            }
            
            // Close the directory handle
            closedir($handle);
        }
        ?>
    </ul>
</body>
</html>

This will list the files and create links that open in a new window. Just like a regular server index page:

<!DOCTYPE html>
<html>
<head>
    <title>Index of Files</title>
</head>
<body>
    <h1>Index of Files</h1>
    <ul>
        <?php
        // Get the current directory
        $dir = '.';
        
        // Open a directory handle
        if ($handle = opendir($dir)) {
            // Loop through each file in the directory
            while (false !== ($file = readdir($handle))) {
                // Exclude directories and the current/parent directory entries
                if ($file != "." && $file != ".." && !is_dir($file)) {
                    // Generate the link to the file
                    $link = $dir . '/' . $file;
                    
                    // Output the link
                    echo '<li><a href="' . $link . '" target="_blank">' . $file . '</a></li>';
                }
            }
            
            // Close the directory handle
            closedir($handle);
        }
        ?>
    </ul>
</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文