What are best practices for validating and sanitizing user input before including files in PHP?

When including files in PHP, it is crucial to validate and sanitize user input to prevent security vulnerabilities such as directory traversal attacks. One best practice is to use functions like realpath() to resolve the absolute path of the file before including it. Additionally, you can use functions like basename() to extract the filename and ensure it does not contain any malicious characters.

$user_input = $_GET['file'];

// Validate and sanitize user input
$validated_file = basename($user_input);
$absolute_path = realpath("path/to/files/" . $validated_file);

// Include the file if it exists
if ($absolute_path !== false && file_exists($absolute_path)) {
    include $absolute_path;
} else {
    echo "Invalid file";
}