How can PHP developers protect their websites from vulnerabilities like directory traversal attacks when including files dynamically?
Directory traversal attacks can be prevented by ensuring that any user input used to include files dynamically is properly sanitized and validated. One way to protect against this vulnerability is to check if the requested file is within a specific directory or whitelist of allowed directories before including it.
$allowed_dir = "/path/to/allowed/directory/";
$file = $_GET['file'];
if (strpos($file, '..') === false && file_exists($allowed_dir . $file)) {
include($allowed_dir . $file);
} else {
// Handle error or redirect to a safe page
echo "Invalid file requested";
}