How to List A Directory Contents Using PHP (Recursive)

To list contents of a directory is simple in PHP, just use three PHP directory functions, opendir,  readdir and is_dir.

The code:

function listDirectory($path)
    $handle = @opendir($path);

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

        if ( is_dir("$path/$file")) {
            echo "$path/$file\n";
        } else {
            echo "$path/$file\n";



Here’s the result:

Directory List Using PHP

Directory List Using PHP

To start list contents, first open the directory handle using opendir then loop to read the entire contents using readdir. Check if content is a directory or a file using is_dir, if a directory,  then call function listDirectory to read it’s content (recursive).TV6CA39U8TTG

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather


Leave a Reply

Your email address will not be published. Required fields are marked *