How can PHP developers optimize the code provided to handle cookie acceptance more efficiently?

The issue with the current code is that it checks for cookie acceptance on every page load, which can be inefficient. To optimize this, we can set a session variable upon cookie acceptance and only check for this variable on subsequent page loads.

<?php
session_start();

if(isset($_POST['accept_cookies'])){
    $_SESSION['cookies_accepted'] = true;
}

$cookies_accepted = isset($_SESSION['cookies_accepted']) ? $_SESSION['cookies_accepted'] : false;

if(!$cookies_accepted){
    // Show cookie acceptance message
    echo "This website uses cookies. Do you accept?";
    echo "<form method='post'><button type='submit' name='accept_cookies'>Accept</button></form>";
}
?>