How can PHP developers optimize the performance of CAPTCHA scripts to prevent issues like mismatched codes?

To optimize the performance of CAPTCHA scripts and prevent issues like mismatched codes, PHP developers can implement measures such as using session variables to store the CAPTCHA code and comparing it with the user input. This ensures that the code remains consistent throughout the verification process.

<?php
session_start();

// Generate random CAPTCHA code
$captcha_code = rand(1000, 9999);

// Store the CAPTCHA code in a session variable
$_SESSION['captcha_code'] = $captcha_code;

// Display the CAPTCHA image with the generated code
echo '<img src="captcha_image.php" alt="CAPTCHA Image">';

// Validate user input against the stored CAPTCHA code
if(isset($_POST['captcha_input'])){
    if($_POST['captcha_input'] == $_SESSION['captcha_code']){
        echo 'CAPTCHA code matched!';
    } else {
        echo 'CAPTCHA code mismatched!';
    }
}
?>