What best practices should be followed when implementing a theme switcher with cookies in PHP?

When implementing a theme switcher with cookies in PHP, it is important to securely handle user input and set cookies to store the selected theme preference. To ensure a smooth user experience, the theme switcher should check for existing cookies before applying the selected theme. Additionally, the code should include error handling to address any issues that may arise during the theme switching process.

<?php
// Check if a theme has been selected
if(isset($_GET['theme'])) {
    // Validate and sanitize theme input
    $selected_theme = htmlspecialchars($_GET['theme']);
    
    // Set a cookie to store the selected theme
    setcookie('theme', $selected_theme, time() + (86400 * 30), '/');
    
    // Redirect to the current page to apply the selected theme
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Check if a theme cookie exists
if(isset($_COOKIE['theme'])) {
    $current_theme = $_COOKIE['theme'];
} else {
    $current_theme = 'default'; // Set a default theme
}

// Include the selected theme CSS file
echo '<link rel="stylesheet" type="text/css" href="themes/' . $current_theme . '.css">';
?>