首页 > 解决方案 > recaptcha v2 的基本服务器集成

问题描述

有人可以帮我吗?我已经尝试了几个月,但只在 YouTube 和 Google 等上遇到了令人困惑的信息。

我正在为时事通讯构建订阅表格。它只是一个电子邮件字段和一个提交按钮。我得到了一个非常简单的 php 代码,它可以正常工作,但是没有 recaptcha,它就会暴露给机器人:

<?php $email = $_POST['email'];
$formcontent="From: $email \n";
$recipient = "contact@myemail.com";
$subject = "Subscribe";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "You have subscribed. You may close this tab now etc etc.";
?>

这就是我所需要的。此代码位于 mail.php 文件中,我在表单中使用 action="mail.php",该表单位于单独的 html 文件中。

任何人都可以为我建议额外的代码来简单地添加 SecretKey 并进行一些基本的服务器集成 recaptcha 吗?我无法理解 Google 信息网站。他们使用我从未遇到过的术语。我不知道他们想说什么。

标签: phpserverrecaptcha

解决方案


如果你有 recaptcha 在表单上工作,那么在提交表单时,PHP 中的 $_POST 将具有“g-recaptcha-response”。然后,您可以使用 curl 向 Google 发出 API 请求以验证他们的响应。

以下是非常基础的内容,未经测试。您将需要在这方面做更多的工作以改善用户体验,例如使用 Ajax

<?php

function verifyRecaptcha($response)
{
  //Replace the below with your secret key
  $recaptchaSecret = '<google_recaptcha_secret_key>';

  $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, array(
      'secret' => $recaptchaSecret,
      'response' => $response,
  ));

  $output = curl_exec($ch);
  curl_close($ch);

  //the response from Google will be a json string so decode it
  $output = json_decode($output);

  //one of the response keys is "success" which is a boolean
  return $output->success;
}

//First filter the POSTed data
$email = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL);
$captchaResponse = filter_input(INPUT_POST,'g-recaptcha-response',FILTER_SANITIZE_STRING);

//If either email or catcha reponse is missing then one or both were not completed before submit
if(empty($email) || empty($captchaResponse))
{
  //TODO: Better error handling here
  echo "There was an error with the submitted data.";
}
elseif(!verifyRecaptcha($captchaResponse))  //this calls the above function to make the curl request
{
  //TODO: Better error handling here
  echo "Recaptcha verification failed.";
}
else
{
  //I would suggest you don't use their email as the "From" address, rather it should be a domain
  //that is allowed to send email from the server
  //Instead you want to use their email as the "Reply-To" address
  $formcontent = "From: $email \n";
  $recipient = "contact@myemail.com";
  $subject = "Subscribe";
  $mailheader = "From: $email \r\n";
  mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
  echo "You have subscribed. You may close this tab now etc etc.";
}

推荐阅读