How can PHP sessions be effectively utilized to store and verify a visual confirmation code in a guestbook to prevent spam bots?

To prevent spam bots from submitting entries in a guestbook, a visual confirmation code can be implemented. This code is generated and stored in a PHP session when the guestbook form is displayed. When the form is submitted, the entered code is compared with the one stored in the session to verify the user's input.

<?php
session_start();

// Generate a random code and store it in a session
$confirmationCode = rand(1000, 9999);
$_SESSION['confirmation_code'] = $confirmationCode;

// Display the code in the guestbook form
echo "Enter the code: <img src='generate_image.php?code=$confirmationCode' />";

// Verify the code when the form is submitted
if(isset($_POST['confirmation_code'])){
    if($_POST['confirmation_code'] == $_SESSION['confirmation_code']){
        // Code is correct, process the form submission
    } else {
        // Code is incorrect, display an error message
        echo "Incorrect confirmation code. Please try again.";
    }
}
?>