How can the use of CAPTCHA or time measurement be integrated into PHP scripts to prevent spam bots from submitting contact forms?

Spam bots can be prevented from submitting contact forms by integrating CAPTCHA or time measurement into PHP scripts. CAPTCHA requires users to complete a challenge that bots typically can't solve, while time measurement can detect if a form is submitted too quickly, indicating automated activity.

// Example of integrating CAPTCHA into a PHP contact form script
if ($_POST['captcha'] != $_SESSION['captcha_code']) {
    // CAPTCHA code does not match
    // Handle error or prevent form submission
} else {
    // CAPTCHA code matches, process form submission
}

// Example of integrating time measurement into a PHP contact form script
$submit_time = time(); // Get the current timestamp
$last_submit_time = $_SESSION['last_submit_time']; // Get the timestamp of the last form submission
if ($submit_time - $last_submit_time < 5) {
    // Form submitted too quickly, likely automated activity
    // Handle error or prevent form submission
} else {
    // Allow form submission and update last submit time
    $_SESSION['last_submit_time'] = $submit_time;
}