How can PHP developers prevent sensitive information from being exposed when accessing external files using fopen()?

PHP developers can prevent sensitive information from being exposed when accessing external files using fopen() by ensuring that the file path is properly sanitized and validated before opening it. This can be done by checking if the file path is within a specific directory or using a whitelist of allowed file paths. Additionally, developers should avoid using user input directly in the file path to prevent directory traversal attacks.

// Example of sanitizing and validating file path before opening it with fopen()
$allowed_directory = "/path/to/allowed/directory/";
$file_path = $allowed_directory . $_GET['file'];

if (strpos($file_path, $allowed_directory) === 0 && file_exists($file_path)) {
    $file_handle = fopen($file_path, 'r');
    // Read or manipulate file contents here
    fclose($file_handle);
} else {
    // Handle error or prevent access to unauthorized files
    echo "Unauthorized access to file.";
}