PHP directory listing

List files in a directory

scandir() is convenient for a simple listing. Skip the dot entries, escape output sent to HTML, and do not expose private server paths to visitors.

$dir = __DIR__ . '/docs';
foreach (scandir($dir) as $name) {
    if ($name === '.' || $name === '..') {
        continue;
    }
    echo htmlspecialchars($name) . '<br>';
}

The examples below show additional variations and practical file-handling cases.

$handle=opendir("."); // open the current directory
$handle=opendir("E:\\my_dir\\"); // OR use the path 

while (($file = readdir($handle))!==false) {
echo "$file <br>";
}
closedir($handle);
Many times we have to display the list of files in a directory. We can keep the script in any location and by using the file path we can display the files inside the directory.

opendir():
Open the directory handle, returns False on failure.
readdir():
Read entry from directory handle.
closedir():
Close directory handle

Reading and displaying images from a directory

Filter by an allowlist of expected extensions and HTML-escape the generated URL. For uploaded files, server-side MIME validation is still required before storage.

$path = 'images/';
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
foreach (scandir($path) as $file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    if (in_array($ext, $allowed, true)) {
        $src = $path . rawurlencode($file);
        echo '<img src="' . htmlspecialchars($src, ENT_QUOTES, 'UTF-8') . '" alt=""><br>';
    }
}
You can also list the files and directories by using dir function scandir()

Example: Recursively Listing Files in Subdirectories

function listDirectory($dir) {
    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                listDirectory($path);
            } else {
                echo $path . "
";
            }
        }
    }
}

listDirectory('E:\\dir-name\\sub-dir');

Example: Sorting Files by Last Modified Date

$dir = 'your-directory';
$files = scandir($dir);
usort($files, function($a, $b) use ($dir) {
    return filemtime("$dir/$b") - filemtime("$dir/$a");
});

foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo "$file - " . date("F d Y H:i:s", filemtime("$dir/$file")) . "<br>";
    }
}

Example: Filtering Specific File Types

$dir = 'your-directory';
$files = scandir($dir);

foreach ($files as $file) {
    if (preg_match('/\.txt$/', $file)) {
        echo $file . "<br>";
    }
}

Directory Functions
PHP File handling


Subscribe to our YouTube Channel here



plus2net.com







06-07-2021

Superb




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer