Skip to content
PHP Logo

How can I optimize my PHP script to efficiently list and display folders in a web application?

To optimize your PHP script for listing and displaying folders in a web application, you can use the opendir() and readdir() functions to efficiently read the contents of a directory. You can also use the glob() function to get an array of files and directories matching a specified pattern. Finally, consider implementing caching mechanisms to reduce the number of file system calls and improve performance.

php
$dir = 'path/to/directory';

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' && $file != '..') {
                echo "Filename: " . $file . "<br>";
            }
        }
        closedir($dh);
    }
}