Coder Perfect

PHP script to loop through all of the files in a directory?

Problem

I’m seeking for a PHP script that loops over all of the files in a directory so that I can format, print, or add the filename to a link. I’d like to be able to sort the files by name, kind, or creation/modification date. (Think “index” in a fancy directory.) I’d also like to be able to exclude files from the list, such as the script or other “system” files. (Like the “directories”. and..)

I’m more interested in looking at the PHP docs and learning how to develop one myself because I’d like to be able to tweak the script. Please let me know if there are any existing scripts, tutorials, or other resources.

Asked by Moshe

Solution #1

The DirectoryIterator can be used. The following is an example from the php manual:

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

Answered by Morfildur

Solution #2

Try this if you don’t have access to the DirectoryIterator class:

<?php
$path = "/path/to/files";

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        // do something with the file
    }
    closedir($handle);
}
?>

Answered by NexusRex

Solution #3

Use the scandir() function to find a directory:

<?php
    $directory = '/path/to/files';

    if (!is_dir($directory)) {
        exit('Invalid diretory path');
    }

    $files = array();
    foreach (scandir($directory) as $file) {
        if ($file !== '.' && $file !== '..') {
            $files[] = $file;
        }
    }

    var_dump($files);
?>

Answered by ChorData

Solution #4

FilesystemIterator is also a viable option. It uses even less code than DirectoryIterator and eliminates automatically. in addition…

// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');

$entries = array();
foreach ($fileSystemIterator as $fileInfo){
    $entries[] = $fileInfo->getFilename();
}

var_dump($entries);

//OUTPUT
object(FilesystemIterator)[1]

array (size=14)
  0 => string 'aa[1].jpg' (length=9)
  1 => string 'Chrysanthemum.jpg' (length=17)
  2 => string 'Desert.jpg' (length=10)
  3 => string 'giphy_billclinton_sad.gif' (length=25)
  4 => string 'giphy_shut_your.gif' (length=19)
  5 => string 'Hydrangeas.jpg' (length=14)
  6 => string 'Jellyfish.jpg' (length=13)
  7 => string 'Koala.jpg' (length=9)
  8 => string 'Lighthouse.jpg' (length=14)
  9 => string 'Penguins.jpg' (length=12)
  10 => string 'pnggrad16rgb.png' (length=16)
  11 => string 'pnggrad16rgba.png' (length=17)
  12 => string 'pnggradHDrgba.png' (length=17)
  13 => string 'Tulips.jpg' (length=10)

Link: http://php.net/manual/en/class.filesystemiterator.php

Answered by Julian

Solution #5

This code can be used to recursively loop around a directory:

$path = "/home/myhome";
$rdi = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

Answered by GameScripting

Post is based on https://stackoverflow.com/questions/4202175/php-script-to-loop-through-all-of-the-files-in-a-directory