What are the security considerations when using $_GET variables to determine page execution in PHP?

Using $_GET variables directly to determine page execution can lead to security vulnerabilities such as injection attacks or unauthorized access. To mitigate these risks, it is important to sanitize and validate any user input before using it in your PHP code. One way to do this is by using a whitelist approach, where you explicitly define which values are allowed for the $_GET variable.

// Sanitize and validate the $_GET variable before using it
$allowed_pages = ['home', 'about', 'contact'];

$page = isset($_GET['page']) && in_array($_GET['page'], $allowed_pages) ? $_GET['page'] : 'home';

// Execute the page based on the sanitized input
switch ($page) {
    case 'home':
        include 'home.php';
        break;
    case 'about':
        include 'about.php';
        break;
    case 'contact':
        include 'contact.php';
        break;
    default:
        include '404.php';
        break;
}