How can user input affect the security of PHP includes?

User input can affect the security of PHP includes if it is not properly sanitized or validated. If user input is directly used in include or require statements, it can lead to directory traversal attacks or arbitrary code execution. To mitigate this risk, always validate and sanitize user input before using it in include statements. Additionally, use whitelists to restrict the allowed input values.

$user_input = $_GET['file'];

// Validate and sanitize user input
if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', $user_input)) {
    $file_path = 'includes/' . $user_input . '.php';
    
    // Check if the file exists before including it
    if (file_exists($file_path)) {
        include $file_path;
    } else {
        echo 'File not found';
    }
} else {
    echo 'Invalid input';
}