How can PHP developers prevent local file inclusion vulnerabilities when working with file names?

Local file inclusion vulnerabilities can be prevented by validating user input and ensuring that file names are properly sanitized before being used in file operations. Developers should avoid directly including user input in file paths and should instead use predefined file paths or whitelist approved file names. Additionally, using functions like realpath() can help resolve file paths to their absolute form and prevent directory traversal attacks.

// Example of preventing local file inclusion vulnerability by sanitizing user input
$allowed_files = ['file1.txt', 'file2.txt', 'file3.txt']; // Whitelist of approved file names

$user_file = $_GET['file']; // User input for file name
if (in_array($user_file, $allowed_files)) {
    $file_path = realpath('path/to/files/' . $user_file); // Resolve file path to absolute form
    if ($file_path !== false) {
        // Perform file operations using $file_path
    } else {
        // Handle invalid file path
    }
} else {
    // Handle unauthorized file access
}