Skip to content
PHP Logo

What potential issues can arise from not filtering out "." and ".." when listing files in a directory with PHP?

Not filtering out "." and ".." when listing files in a directory with PHP can lead to security vulnerabilities such as directory traversal attacks. To solve this issue, you can use the `is_dir()` function to check if the file is a directory and exclude "." and ".." from the listing.

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

if ($handle = opendir($directory)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if (is_dir($directory . '/' . $file)) {
                echo "Directory: $file\n";
            } else {
                echo "File: $file\n";
            }
        }
    }
    closedir($handle);
}