What potential security risks are associated with using opendir() in PHP to read directories?

Using opendir() in PHP to read directories can potentially lead to security risks such as directory traversal attacks if user input is not properly sanitized. To mitigate this risk, it is important to validate and sanitize user input before passing it to opendir(). This can be done by using functions like realpath() to ensure that the path is valid and does not allow access to directories outside of the intended scope.

$dir = '/path/to/directory';
$validated_dir = realpath($dir);

if ($validated_dir) {
    $handle = opendir($validated_dir);
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }
    closedir($handle);
} else {
    echo "Invalid directory path";
}