What are the potential pitfalls of using diropen() function in PHP for file manipulation?

Using diropen() function in PHP for file manipulation can lead to security vulnerabilities such as directory traversal attacks, where an attacker can access files outside of the intended directory. To prevent this, it is recommended to use the realpath() function to get the full path of the directory before performing any file operations.

$directory = '/path/to/directory/';
$real_directory = realpath($directory);

if($real_directory !== false){
    // Perform file operations using $real_directory
} else {
    // Handle error
}