Getting the names of all files in a directory with

2019-01-01 09:05发布

问题:

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?

回答1:

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

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


回答2:

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.



回答3:

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


回答4:

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



回答5:

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 globe 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.


回答6:

I have smaller code todo this:

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


回答7:

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

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


回答8:

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


回答9:

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


回答10:

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


回答11:

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



回答12:

Here´s a more advanced example for showing all files in a folder



回答13:

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>\";
?>


回答14:

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



回答15:

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
            */
        }
    }
}