【问题标题】:verifying recaptcha in php在php中验证recaptcha
【发布时间】:2019-05-20 03:07:07
【问题描述】:

我有一个简单的.html 联系表格,其中添加了recaptcha,并且我有一个相应的.php 文件设置为通过我的电子邮件将填充的表格字段信息发送回给我。提交表单后,我将用户重定向到我的主页。我试图弄清楚需要哪些代码才能将 recaptcha 验证添加到 .php 文件以及在哪里,同时仍保留我已经设置的功能。

html代码:

<script src='https://www.google.com/recaptcha/api.js' async defer>
</script>

<form method="post" action="mail.php">
  <input id="name" name="name" placeholder="Name" required />
  <input id="email" name="email" placeholder="Email" type="email" required />
  <textarea id="message" name="message" placeholder="Question/Comment" required></textarea>
  <div class="g-recaptcha" data-sitekey="MY SITE KEY"></div>
  <input class="btn-success formBtn" name="submit" type="submit" />
  <input class="formBtn" type="reset" />
</form>

php代码:

<?php 

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $formcontent="From: $name \n Message: $message";
    $recipient = "MY EMAIL";
    $subject = "Contact Form";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or 
   die("Error!");
   header('Location: /');

?>

【问题讨论】:

标签: php html recaptcha verification


【解决方案1】:

您的 html 代码看起来不错,您可以尝试以下 php 代码,看看它是否适用于您的表单。还要确保您使用的是 v2 reCaptcha 密钥。

php代码

<?php 
if(isset($_REQUEST['submit'])){
  $captcha = $_REQUEST['g-recaptcha-response'];
  $handle = curl_init('https://www.google.com/recaptcha/api/siteverify');
  curl_setopt($handle, CURLOPT_POST, true);
  curl_setopt($handle, CURLOPT_POSTFIELDS, "secret=YOUR_SECRET_KEY&response=$captcha");
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($handle);
  $explodedArr = explode(",",$response);
  $doubleExplodedArr = explode(":",$explodedArr[0]);
  $captchaConfirmation = end($doubleExplodedArr);

  if(trim($captchaConfirmation) == "true") {

    $to ='example@email.com';
    $subject = 'Form';
    $headers = "From: " . $_POST['email'] . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $message = '';
    $message .= "<strong>First Name:</strong> " .$_POST['name'] ;
    $message .= "<strong>Email:</strong> " . $_POST['email'];
    $message .= "<strong>Message:</strong> " . $_POST['message'] ; 
    $send = mail($to, $subject, $message, $headers);
    if($send) {
      echo "Message Sent. Thank You!";
    } else {
      echo "<script> alert('Message Not Sent. Please try again.";
    }

  } else {
    echo "Captcha entry was wrong. Please try again.";
  }
} 
?>

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 2015-11-05
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多