我试图将Google reCaptcha V3添加到表单中,我进行了搜索,发现了另一个问题的一些文章和一些代码片段。
它不是带有复选框的,而是显示在右下角或页面上。
这是HTML代码:
<script src='https://www.google.com/recaptcha/api.js?render=My Website Key'></script>
</head>
JS代码:
<body>
<script>
//When page is loaded
$(document).ready(function() {
//When recaptcha is ready
grecaptcha.ready(function() {
grecaptcha.execute('The Website Key', {action: 'homepage'}).then(function(token) {
//Add token element at the end of the form
$('#mailForm').prepend('<input type="hidden" name="token" value="' + token + '">');
//Add action element at the end of the form
$('#mailForm').prepend('<input type="hidden" name="action" value="homepage">');
});
}); //Recaptcha ready
}); //Page is loaded
</script>
表格:
<form action='php/mail.php' method="post" id='mailForm' enctype='multipart/form-data'>
//Some inputs
</form>
PHP代码:
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
$secret = 'My Secret Key';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//Send the mail
}else{
echo 'Please check reCaptcha';
}
}else{
echo 'Please check reCaptcha';
}
因此,在加载页面时会更新令牌,因此,如果用户由于任何原因再次尝试,它将无法正常工作,并且会收到错误消息。
那么,当用户提交表单时,我应该更新令牌吗?否则可能会导致垃圾邮件?或者在这种情况下我该怎么办?