What are the potential pitfalls of using include() to load new pages in PHP and how can they be avoided?

Using include() to load new pages in PHP can potentially lead to security vulnerabilities such as directory traversal attacks if user input is not properly sanitized. To avoid this, always validate and sanitize user input before passing it to include() to prevent malicious users from accessing sensitive files on the server.

// Sanitize user input before using include()
$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING);
if ($page) {
    include('pages/' . $page . '.php');
} else {
    // Handle invalid input
    echo 'Invalid page requested';
}