How to get file names?

For example, we have a folder /images/, inside it there are some files.

And script /scripts/listing.php

How can we get the names of all the files inside a folder /images/in listing.php?

Thank.

+5
source share
5 answers
<?php

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

See: readdir ()

+8
source

Even simpler than readdir (), use glob:

$files = glob('/path/to/files/*');

Additional Info About glob

+3
source

scandir dir . , . .. , 0, scandir array_diff array_merge:

$files = array_merge(array_diff(scandir($dir), Array('.','..')));
// $files now contains the filenames of every file in the directory $dir
+2

, SPL DirectoryIterator:

<?php

foreach (new DirectoryIterator('../images') as $fileInfo) 
{
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

?>
+2

Enrico, /.

class Directory
{
    private $path;
    public function __construct($path)
    {
        $path = $path;
    }

    public function getFiles($recursive = false,$subpath = false)
    {
        $files = array();
        $path = $subpath ? $subpath : $this->path;

        if(false != ($handle = opendir($path))
        {
            while (false !== ($file = readdir($handle)))
            {
                if($recursive && is_dir($file) && $file != '.' && $file != '..')
                {
                    array_merge($files,$this->getFiles(true,$file));
                }else
                {
                    $files[] = $path . $file;
                }
            }
        }
        return $files;
    }
}

:

<?php
$directory = new Directory("/");
$Files = $directory->getFiles(true);
?>

:

/index.php
/includes/functions.php
/includes/.htaccess
//...

hoep .

+1
source

All Articles