What are some alternative methods to safely include files based on user input in PHP?

When including files based on user input in PHP, it is important to validate and sanitize the input to prevent directory traversal attacks. One way to safely include files is to use a whitelist approach, where only files from a predefined list are allowed to be included.

// Validate user input
$user_input = $_GET['file'];
$allowed_files = ['file1.php', 'file2.php', 'file3.php'];

// Check if the user input is in the allowed list
if (in_array($user_input, $allowed_files)) {
    include($user_input);
} else {
    echo "Invalid file";
}