What are the potential security risks associated with including files using variables in PHP?

Including files using variables in PHP can lead to security risks such as directory traversal attacks, where an attacker could manipulate the variable to include files from outside the intended directory. To mitigate this risk, it is important to sanitize and validate the variable before including the file.

// Sanitize and validate the variable before including the file
$filename = 'path/to/directory/' . basename($_GET['file']);
if (file_exists($filename)) {
    include $filename;
} else {
    echo 'File not found';
}