在php

时间:2019-05-20 03:07:08

标签: php html recaptcha verification

我有一个添加了Recaptcha的简单.html联系人表单,并且我设置了一个相应的.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: /');

?>

1 个答案:

答案 0 :(得分:0)

您的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.";
  }
} 
?>