How can the use of $_GET variables in file inclusions in PHP lead to potential security risks and how can they be prevented?

Using $_GET variables directly in file inclusions can lead to security risks such as directory traversal attacks, where an attacker can access sensitive files on the server. To prevent this, always sanitize and validate user input before using it in file inclusions.

// Sanitize and validate the $_GET variable before using it in file inclusions
if(isset($_GET['page']) && preg_match('/^[a-zA-Z0-9_]+$/', $_GET['page'])) {
    $page = $_GET['page'];
    include('pages/' . $page . '.php');
} else {
    // Handle invalid input
    echo 'Invalid page requested';
}