What is the purpose of using reCAPTCHA in PHP forms and how does it help prevent spam?

reCAPTCHA is used in PHP forms to prevent spam by verifying that the user submitting the form is not a bot. It presents a challenge that only humans can solve, such as identifying objects in images or solving simple puzzles. This helps to ensure that the form submissions are legitimate and not automated spam.

<?php
// Include reCAPTCHA library
require_once('recaptchalib.php');

// Your reCAPTCHA keys
$siteKey = 'YOUR_SITE_KEY';
$secretKey = 'YOUR_SECRET_KEY';

// Verify reCAPTCHA response
$recaptcha = new ReCaptcha($secretKey);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

if (!$resp->isSuccess()) {
    // reCAPTCHA verification failed, handle error
    echo "reCAPTCHA verification failed, please try again.";
} else {
    // reCAPTCHA verification successful, process form submission
    // Add your form processing logic here
}
?>