Getting the names of all files in a directory with PHP

PhpFileDirectoryFilenames

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

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

Solution 2 - Php

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.

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

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

Solution 6 - Php

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

Solution 7 - Php

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

Solution 8 - Php

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

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

Solution 9 - Php

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

Solution 10 - Php

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

Solution 11 - Php

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

Solution 12 - Php

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

Solution 13 - Php

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

Solution 14 - Php

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

Solution 15 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDexterWView Question on Stackoverflow
Solution 1 - PhpTatu UlmanenView Answer on Stackoverflow
Solution 2 - PhpIlijaView Answer on Stackoverflow
Solution 3 - PhpAliwebView Answer on Stackoverflow
Solution 4 - PhpMike MooreView Answer on Stackoverflow
Solution 5 - PhpFletcher MooreView Answer on Stackoverflow
Solution 6 - PhpYooRich.comView Answer on Stackoverflow
Solution 7 - PhpTheCrazyProfessorView Answer on Stackoverflow
Solution 8 - PhpircmaxellView Answer on Stackoverflow
Solution 9 - PhpDanijelView Answer on Stackoverflow
Solution 10 - PhpAd KahnView Answer on Stackoverflow
Solution 11 - Phpjim_kastrinView Answer on Stackoverflow
Solution 12 - PhpmerraisView Answer on Stackoverflow
Solution 13 - PhpChandreshView Answer on Stackoverflow
Solution 14 - PhpPrashant GoelView Answer on Stackoverflow
Solution 15 - PhpKaloyView Answer on Stackoverflow