What potential security risks are involved in including files in PHP, especially when including files that include other files?

When including files in PHP, especially when including files that include other files, there is a risk of including files from untrusted sources or inadvertently including sensitive files that could compromise the security of the application. To mitigate this risk, it is important to use absolute file paths and sanitize user input to prevent directory traversal attacks.

// Example of including files with absolute paths and sanitizing user input
$allowed_files = array("file1.php", "file2.php", "file3.php");
$file = isset($_GET['file']) ? $_GET['file'] : 'default.php';

if (in_array($file, $allowed_files)) {
    include_once(__DIR__ . '/' . $file);
} else {
    echo "Invalid file requested.";
}