How can one effectively compare user input with the generated captcha in PHP to verify correctness?

To compare user input with the generated captcha in PHP, you can store the generated captcha value in a session variable when it is created. Then, when the user submits their input, you can compare it with the value stored in the session to verify correctness.

// Start the session
session_start();

// Generate a random captcha value
$captcha = rand(1000, 9999);

// Store the captcha value in a session variable
$_SESSION['captcha'] = $captcha;

// Display the captcha image with the generated value
echo "<img src='generate_captcha_image.php?code=".$captcha."' />";

// Check user input against the stored captcha value
if(isset($_POST['captcha_input'])){
    if($_POST['captcha_input'] == $_SESSION['captcha']){
        echo "Captcha verification successful!";
    } else {
        echo "Captcha verification failed. Please try again.";
    }
}