What potential security issues can arise when using opendir() function in PHP?

One potential security issue when using the opendir() function in PHP is the possibility of directory traversal attacks, where an attacker can manipulate the input to access files outside of the intended directory. To prevent this, it is important to sanitize user input and validate the directory path before passing it to the opendir() function.

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

// Sanitize and validate the directory path
if (strpos($directory, "../") === false) {
    // Open the directory safely
    if ($handle = opendir($directory)) {
        // Process the directory contents
        while (false !== ($entry = readdir($handle))) {
            echo $entry . "<br>";
        }
        closedir($handle);
    } else {
        echo "Failed to open directory";
    }
} else {
    echo "Invalid directory path";
}