How can CAPTCHA be effectively implemented in a PHP form mailer to prevent spam?

To prevent spam in a PHP form mailer, CAPTCHA can be effectively implemented by adding a CAPTCHA field to the form that users must complete before submitting. This helps verify that the form is being filled out by a human and not a bot. The CAPTCHA field can generate a random code or image that the user needs to input correctly to proceed with the form submission.

// Generate a random CAPTCHA code
$captcha_code = substr(md5(rand()), 0, 6);

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

// Add the CAPTCHA field to the form
echo '<label for="captcha">Please enter the code shown above:</label>';
echo '<input type="text" id="captcha" name="captcha" required>';
echo '<img src="captcha_image.php" alt="CAPTCHA Image">'; // Display CAPTCHA image

// Validate the CAPTCHA code on form submission
if(isset($_POST['captcha']) && $_POST['captcha'] == $_SESSION['captcha_code']) {
    // CAPTCHA code is correct, proceed with form submission
} else {
    // CAPTCHA code is incorrect, display an error message
    echo 'Incorrect CAPTCHA code. Please try again.';
}