What potential pitfalls should be considered when including template files in PHP, and how can they be avoided?

Potential pitfalls when including template files in PHP include security vulnerabilities such as directory traversal attacks and file inclusion vulnerabilities. To avoid these pitfalls, it is important to sanitize user input, validate file paths, and restrict access to sensitive directories.

// Example of including a template file securely
$template_file = 'templates/' . basename($_GET['template']); // Sanitize user input
if (strpos($template_file, 'templates/') === 0 && file_exists($template_file)) { // Validate file path
    include $template_file; // Include the template file
} else {
    echo 'Invalid template file';
}