How can PHP developers ensure that their websites comply with legal requirements for user consent without sacrificing user experience?

To ensure websites comply with legal requirements for user consent without sacrificing user experience, PHP developers can implement a cookie consent banner that informs users about the use of cookies and allows them to provide explicit consent before any cookies are set. This can be achieved by creating a simple PHP script that displays the banner to users and sets a cookie only if the user consents.

<?php
if (!isset($_COOKIE['cookie_consent'])) {
    echo '<div id="cookie-banner">
            This website uses cookies. By continuing to use this site, you are agreeing to our use of cookies.
            <button onclick="setCookie()">I agree</button>
          </div>';
}

if (isset($_POST['cookie_consent'])) {
    setcookie('cookie_consent', 'true', time() + (86400 * 30), '/');
}

?>
<script>
function setCookie() {
    document.getElementById('cookie-banner').style.display = 'none';
    fetch(window.location.href, {
        method: 'POST',
        body: 'cookie_consent=true',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    });
}
</script>