Traverse a directory in php


Sometimes, we need to traverse a directory. Here is the code to traverse a directory/folder.

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
       // do something...
    }
    closedir($handle);
}

Exclude current and parent directory

The above code display all the files and sub-directories in a current directory, including your current directory (“.”) and parent directory (“..”). To exclude these directories you can check the file name.

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}

Exclude all subdirectories

Sometimes we need only files and don’t want subdirectories while traversing. This will fetch all files.

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if (!is_dir($file)) {
            echo "$file\n";
        }
    }
    closedir($handle);
}

Traverse only specific file type

Suppose you want to fetch files of a specific type like traversing only HTML files. You can use pathinfo function.

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
         $extension = pathinfo($file, PATHINFO_EXTENSION);
         if($extension == 'html'){
            echo $file;
         }
    }
    closedir($handle);
}

Traverse and sort directory by last modified dates

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);
}
// sort
 ksort($files);
// reverse
$files = array_reverse($files);
foreach($files as $file) {
echo $file; 
}