What are the potential security risks when including files in PHP, and how can they be mitigated?

One potential security risk when including files in PHP is the possibility of including malicious files that could compromise the security of your application. To mitigate this risk, you should always sanitize user input and validate file paths before including them in your code.

// Sanitize and validate file path before including
$filename = filter_var($_GET['file'], FILTER_SANITIZE_STRING);
if (file_exists($filename)) {
    include $filename;
} else {
    echo "Invalid file path";
}