How can PHP beginners ensure that their code is not vulnerable to directory traversal attacks when including files?

Directory traversal attacks can be prevented by using proper input validation and sanitization techniques when including files in PHP. One way to mitigate this risk is by using the `realpath()` function to get the full path of the file being included and then comparing it against a whitelist of allowed directories.

$allowed_directories = ['/path/to/allowed/directory1', '/path/to/allowed/directory2'];
$included_file = '/path/to/user-input-file';

$real_path = realpath($included_file);

if ($real_path && in_array(dirname($real_path), $allowed_directories)) {
    include $real_path;
} else {
    // Handle error or log unauthorized access attempt
}