What are some best practices for implementing a CAPTCHA system in PHP to prevent spam submissions in contact forms?

To prevent spam submissions in contact forms, implementing a CAPTCHA system in PHP is a common solution. CAPTCHA requires users to complete a challenge to prove they are human, thus reducing automated spam submissions.

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

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

// Display the CAPTCHA image in the form
echo '<img src="captcha.php" alt="CAPTCHA Image">';

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