首页 > 解决方案 > 如何使用 PHP 将 reCAPTCHA v2 添加到现有表单?

问题描述

我想使用 PHP 将 recaptcha 集成到我的功能联系表单中。PHP 表单已经设置好了,所以我想我应该走那条路。我相信

我已经设置了所有必要的变量和参数,我只需要知道在我的 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 标记。

标签: phphtmlrecaptcha

解决方案


你错过了支票。这将在发送消息部分之前进行。像这样的东西:

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);

推荐阅读