What are some best practices for navigating folders and displaying files in PHP?

When navigating folders and displaying files in PHP, it is important to use the appropriate functions provided by PHP to ensure security and efficiency. One common approach is to use the opendir(), readdir(), and closedir() functions to open a directory, read its contents, and close it respectively. Additionally, using functions like is_dir() and is_file() can help determine if a specific item in the directory is a folder or a file before processing it.

$directory = "path/to/directory";

if (is_dir($directory)) {
    if ($handle = opendir($directory)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                if (is_dir($directory . "/" . $file)) {
                    echo "Folder: " . $file . "<br>";
                } else {
                    echo "File: " . $file . "<br>";
                }
            }
        }
        closedir($handle);
    }
}