php - 如何验证是否检查了 reCaptcha
问题描述
如果检查了 Google reCaptcha v2,我正在创建一个应该发送邮件的联系表单。现在,即使检查了 reCaptcha,它也会回显我的文本。
我试过移动 reCaptcha 片段并尝试做一个 if(isset 但似乎不起作用。
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmail = false;
$errorCaptcha = false;
if(empty($name) || empty($email) || empty($subject) || empty($message)){
echo "<span style='color: red;font-weight: bold;'>Fyll i alla fält!</span>";
$errorEmpty = true;
}
if(empty($_POST['g-recaptcha-response'])){
echo "<span style='color: red;font-weight:bold;'>reCaptchan är inte ifylld!</span>";
$errorCaptcha = true;
}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "<span style='color: red;font-weight: bold;'>Du måste skriva in en giltig e-mail adress!</span>";
$errorEmail = true;
}
else{
echo "<span style='color: green;font-weight: bold;'>Ditt meddelande skickades, vi återkommer inom max 3 arbetsdagar!</span>";
}
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$secret = '';
$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){
$to = $email;
$subject = $subject;
$text = "Name: $name\n From: $name\n Message: $message";
$headers = "From: $email";
if($errorEmpty == false && $errorEmail == false && $errorCaptcha == false){
mail($to,$subject,$text,$headers);
}
}
} // ReCaptcha 2
如果检查了 reCaptcha,我希望激活 mail() 函数,否则我想向用户回显文本。
解决方案
很难说你在哪里有问题。您当前的代码将始终echo
显示某种消息(尽管您可能需要显示消息,成功或失败)。
如果您说您无法if($responseData->success){
正确验证复选框,我建议您通过使用查看响应数据var_dump($responseData)
,看看Google是否试图告诉您一些事情(错误的密钥、域名, ETC)。
作为一种替代方法,您可以考虑使用Google 的PHP reCaptcha 库作为处理这种情况的一种更简单的方法——例如我的代码:
function validateRecaptcha(?String $gRecaptchaResponse) {
/* API source from: https://github.com/google/recaptcha */
$recaptcha = new ReCaptcha\ReCaptcha(***SECRET HERE***);
$resp = $recaptcha->verify($gRecaptchaResponse, $_SERVER['REMOTE_ADDR']);
return $resp->isSuccess();
}
PS:小心使用empty
验证用户输入。如果用户决定提交仅0
作为内容的消息,您的if(...|| empty($message)){
检查将失败。
推荐阅读
- python - 通过 REST API(使用 Python)使用 Adobe PDF 服务将 PDF 转换为 DOCX
- json - PowerShell - 读取 JSOn 文件,使用字符串插值
- python - 比较值是列表但具有相同键的 2 个字典
- java - 如何在 Java *with Flutter* 中禁用证书验证?
- xml - Ansible XML - 仅检索匹配的值
- node.js - 如何在带参数的路由中使用正则表达式?
- node.js - 使用 API 密钥 NodeJS 将视频上传到 Youtube
- css - 在 ios 14.6 中选择下拉菜单?
- php - php 中的 CURL 在我的页面中返回显示文本
- java - map.replace() 和 map.put() 用于在 Collection Framework 中更新 Map 中的值的区别