Получение имен всех файлов в каталоге с помощью PHP

По какой-то причине я продолжаю получать '1' для имен файлов с этим кодом:

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

Когда я отображаю каждый элемент в $results_array, я получаю несколько единиц, а не имя файла. Как я могу получить имя файла?

17 ответов

Решение

Не беспокойтесь о open/readdir и используйте glob вместо:

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

Стиль SPL:

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

Проверьте классы DirectoryIterator и SplFileInfo для получения списка доступных методов, которые вы можете использовать.

Поскольку принятый ответ имеет два важных недостатка, я публикую улучшенный ответ для тех новичков, которые ищут правильный ответ:

foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
    // Do something with $file
}
  1. Фильтрация globe результаты функции с is_file необходимо, потому что он может также вернуть некоторые каталоги.
  2. Не все файлы имеют . в их именах, так */* картина отстой в общем.

Вы должны окружить $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 />';
}

Просто используйте glob('*'), Вот документация

У меня есть меньший код для этого:

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

На некоторых ОС вы получаете ... а также .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>$filename}";<br>";
    }
}

Это связано с точностью оператора. Попробуйте изменить это на:

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

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

Вы можете просто попробовать scandir(Path) функция. это быстро и легко реализовать

Синтаксис:

$files = scandir("somePath");

Эта функция возвращает список файлов в массив.

чтобы посмотреть результат, вы можете попробовать

var_dump($files);

Или же

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

Другим способом составления списка каталогов и файлов будет использование RecursiveTreeIterator ответил здесь: /questions/39362727/perechislenie-vseh-papok-podpapok-i-fajlov-v-kataloge-s-ispolzovaniem-php/39362738#39362738.

Тщательное объяснение RecursiveIteratorIterator и итераторы в PHP можно найти здесь: /questions/8752857/kak-rabotaet-recursiveiteratoriterator-v-php/8752858#8752858

Использование:

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

Я кое-что для этого создал:

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

Я просто использую этот код:

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

При этом будут перечислены файлы и созданы ссылки, которые открываются в новом окне. Точно так же, как обычная индексная страница сервера:

      <!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>

Вот более сложный пример для отображения всех файлов в папке

Рекурсивный код для изучения всего файла, содержащегося в каталоге ('$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
            */
        }
    }
}
Другие вопросы по тегам