如何将Google reCAPTCHA v2设置为联系表单必填项?
解决Google reCAPTCHA v2无法设为必填的问题
你的问题核心在于前端没强制校验用户完成验证,后端也没验证Google的响应结果,导致机器人可以直接绕过验证提交表单。下面分两步给你解决:
一、前端添加必填校验(提升用户体验)
先给表单加个提交前的校验,确保用户必须完成“我不是机器人”验证才能提交。在你的页面JS里加这段代码:
// 假设你的表单ID是contact-form,替换成你实际的表单ID document.getElementById('contact-form').addEventListener('submit', function(e) { // 获取reCAPTCHA的响应值 const recaptchaResponse = grecaptcha.getResponse(); if (recaptchaResponse.length === 0) { e.preventDefault(); // 阻止表单提交 alert('请先完成人机验证哦!'); } });
如果你的reCAPTCHA是显式渲染的,记得确保grecaptcha对象能正常访问。
二、后端添加Google响应验证(核心,防绕过)
前端校验只是给用户看的,恶意请求可以直接跳过前端,所以后端必须验证Google返回的结果。修改你的PHP代码,在邮件发送前先做reCAPTCHA验证:
<?php $page_id = 4; $page_details = get_page_details($page_id); ini_set('sendmail_from', ""); require ("class.phpmailer.php"); $mail = new PHPMailer(); // 1. 配置你的reCAPTCHA密钥(从Google控制台获取的Secret Key) $recaptchaSecret = '你的Secret Key'; // 2. 获取前端提交的reCAPTCHA响应和用户IP $recaptchaResponse = $_POST['g-recaptcha-response'] ?? ''; $userIp = $_SERVER['REMOTE_ADDR']; // 3. 向Google发送验证请求 $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify'; $verifyData = http_build_query([ 'secret' => $recaptchaSecret, 'response' => $recaptchaResponse, 'remoteip' => $userIp ]); $verifyContext = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $verifyData ] ]); $verifyResult = json_decode(file_get_contents($verifyUrl, false, $verifyContext), true); if ($_POST["action"] == "sendmail_contact"){ // 先判断reCAPTCHA是否验证通过 if (!$verifyResult['success']) { echo '人机验证失败,请重试!'; exit; // 终止后续代码,不发送邮件 } // 下面是你原来的邮件发送逻辑 $from = $_POST["..."]; // ... 你的其他表单字段处理、邮件发送代码 } ?>
注意事项:
- 把代码里的
你的Secret Key替换成你在Google reCAPTCHA控制台获取的密钥(不是Site Key) - 确保前端的reCAPTCHA组件正常渲染,提交表单时会自动带上
g-recaptcha-response字段 - 后端验证是必须的,别只依赖前端校验,不然恶意请求还是能绕过
内容的提问来源于stack exchange,提问作者vld1
相关产品推荐
相关产品推荐

