Are there any best practices or guidelines recommended for handling cookie consent and opt-out functionalities in PHP to comply with data protection regulations like GDPR?

To comply with data protection regulations like GDPR, it is important to provide users with clear information about cookies, obtain their consent before setting non-essential cookies, and offer them an easy way to opt-out of cookie tracking. One common approach is to use a cookie consent banner that allows users to accept or reject cookies.

<?php
// Check if user has already given consent
if (!isset($_COOKIE['cookie_consent'])) {
    // Display cookie consent banner
    echo '<div id="cookie-banner">
            <p>This website uses cookies to improve user experience. <a href="/privacy-policy">Learn more</a></p>
            <button onclick="acceptCookies()">Accept</button>
            <button onclick="rejectCookies()">Reject</button>
          </div>';
}

// Function to set cookie consent
function setCookieConsent($consent) {
    if ($consent === 'accept') {
        setcookie('cookie_consent', 'true', time() + (86400 * 30), "/"); // Cookie expires in 30 days
    } else {
        setcookie('cookie_consent', 'false', time() + (86400 * 30), "/"); // Cookie expires in 30 days
    }
}

// Handle cookie consent actions
if (isset($_POST['action'])) {
    if ($_POST['action'] === 'accept') {
        setCookieConsent('accept');
    } elseif ($_POST['action'] === 'reject') {
        setCookieConsent('reject');
    }
}

// JavaScript functions to handle cookie consent actions
echo '<script>
        function acceptCookies() {
            document.getElementById("cookie-banner").style.display = "none";
            document.cookie = "cookie_consent=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
        }
        function rejectCookies() {
            document.getElementById("cookie-banner").style.display = "none";
            document.cookie = "cookie_consent=false; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
        }
      </script>';
?>