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

出于某种原因,我一直得到一个’1’的文件名与这个代码:

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

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

157259 次浏览

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

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

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

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

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

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

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

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.

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

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

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.

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

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

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

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

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

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