What potential security risks are associated with using opendir and readdir functions to access files on other servers in PHP?

Using opendir and readdir functions to access files on other servers in PHP can pose security risks such as directory traversal attacks, where an attacker could potentially access sensitive files outside the intended directory. To mitigate this risk, it is important to sanitize user input and validate file paths before using opendir and readdir functions.

$directory = '/path/to/directory/';

// Validate and sanitize user input for directory path
if (strpos($directory, '../') !== false) {
    die('Invalid directory path');
}

$handle = opendir($directory);

// Loop through files in the directory
while (false !== ($file = readdir($handle))) {
    echo "$file\n";
}

closedir($handle);