如何使用PHP将reCAPTCHA v2添加到现有表单?

时间:2019-05-07 18:33:14

标签: php html recaptcha

我想使用PHP将Recaptcha集成到我正常运行的联系表中。 PHP表单已经设置好,所以我认为应该走那条路。我相信

我已经设置了所有必需的变量和参数,我只需要知道将最终的Recaptcha验证确切地放置在PHP表单中的确切位置。

我已经尝试了几次代码迭代,但是它实质上会短路并破坏现有代码的功能。

HTML:

<form action="php/contactform.php" method="post" role="form" class="contactForm" id="contactForm">
  <div class="form-group">
    <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" required />
  </div>
  <div class="form-group">
    <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" required />
  </div>
  <div class="form-group">
    <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" required />
  </div>
  <div class="form-group">
    <textarea class="form-control" name="message" id="message" rows="5" data-rule="required" required placeholder="Message"></textarea>
  </div>
  <div class="g-recaptcha" data-sitekey="SITEKEYCODEALREADYHERE"></div>
  <div class="text-center"><button type="submit" name="submit">Send Message</button></div>

</form>

PHP:

<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
                $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $subject = strip_tags(trim($_POST["subject"]));
                $subject = str_replace(array("\r","\n"),array(" "," "),$subject);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($subject) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "me@cbonilla.dev";

        // Set the email subject.
        $subject = "Subject: $subject";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";

        //reCAPTCHA Verification
        $secretKey = "SECRETCODEALREADYHERE";
        $responseKey = $_POST['g-recaptcha-response'];
        $UserIP = $_SERVER['REMOTE_ADDR'];
        $url = "https://www.google.com/recaptcha/api/siteverify?secret='.$secretkey.'&response='.$responseKey.'&remoteip='.$UserIP.'";

        $response = file_get_contents($url);
        $data = json_decode($response);


        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been submitted, fam.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }
    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    } 

?>

我相信最终的代码段出现在“ //发送电子邮件”之后。注意。我还已经在该部分中添加了reCAPTCHA JS标记。

1 个答案:

答案 0 :(得分:0)

您缺少支票。这将在发送消息之前进行。像这样:

if(!empty($data["success"])) {
   // You could put the actual sending of the mail in here.  Or, not.    
} else {
    echo "Your captcha failed!";
    exit();
}

以上将在您的data = json_decode()行之后出现。

回答您的问题。但是,考虑一下。 Recaptcha(https://developers.google.com/recaptcha/docs/verify)的文档说,调用api端点验证验证码时,必须使用POST。您可以通过curl调用来做到这一点,类似于以下内容:

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'secret' => $secretKey,
        'response' => $captcha,
        'remoteip' => $_SERVER['REMOTE_ADDR']
    ],
    CURLOPT_RETURNTRANSFER => true
]);

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

$data = json_decode($response);