What potential pitfalls should be considered when using the dir() function in PHP scripts?

When using the dir() function in PHP scripts, it's important to consider potential security risks, such as exposing sensitive directory information or inadvertently allowing unauthorized access to directories. To mitigate these risks, always ensure that proper permissions are set on directories and limit the scope of the dir() function to only access directories that are intended for public viewing.

$dir = "/path/to/directory";

// Check if directory exists and is accessible
if (is_dir($dir)) {
    $handle = dir($dir);

    // Loop through directory contents
    while (false !== ($entry = $handle->read())) {
        echo $entry . "<br>";
    }

    $handle->close();
} else {
    echo "Directory does not exist or is not accessible.";
}