如何使用 PHP 联系表单解决 Google Recaptcha 验证问题?

问题描述 投票:0回答:1

我有一个简单的联系表单,在提交表单(电子邮件)时未验证 Google 验证码。

当客户填写表单并勾选验证码框时,表单会验证 Google 验证码,但当您点击提交时,它不会验证验证码是否成功(==true)。

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Set your reCAPTCHA secret key
    $recaptcha_secret = "CAPTCHA_KEY_PLACEHOLDER";
    
    // Verify the reCAPTCHA response
    $recaptcha_response = $_POST['g-recaptcha-response'];
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_data = array(
        'secret' => $recaptcha_secret,
        'response' => $recaptcha_response
    );
    $recaptcha_options = array(
        'http' => array (
            'method' => 'POST',
            'content' => http_build_query($recaptcha_data)
        )
    );
    $recaptcha_context  = stream_context_create($recaptcha_options);
    $recaptcha_result = file_get_contents($recaptcha_url, false, $recaptcha_context);
    $recaptcha_json = json_decode($recaptcha_result);
    
    // Check if the reCAPTCHA verification was successful
    if ($recaptcha_json->success == true) {
        // Proceed with form submission
        if (isset($_POST['fullName']) && isset($_POST['email']) && isset($_POST['subject'])) {
            //Variables to read from HTML -> PHP
            $fullName = $_POST['fullName'];
            $email = $_POST['email'];
            $message = $_POST['subject']; 

            //Reply messages
            $to = "EMAIL_ADDRESS_PLACEHOLDER";
            $subject = "Contact form submission from $fullName";
            $headers = "From: $email" . "\r\n" . "Reply-To: $email" . "\r\n" . "X-Mailer: PHP/" . phpversion();

            //Conditional submit message
            if (mail($to, $subject, $message, $headers)) {
                echo "<script>alert('Thank you! your message has been sent.');</script>";
            } else {
                echo "<script>alert('Something has gone wrong, try again or refresh the page..');</script>";
            }
        }
    } else {
        // Display an error message and don't allow form submission
        echo "<script>alert('Please enter the reCaptcha verification before submission of forms.');</script>";
    }
}
?>
php validation recaptcha contact-form
1个回答
0
投票

您可以 var_dump($recaptcha_json);在检查之前,看看解码数据背后究竟发生了什么。

应提供最终的错误代码和描述。

© www.soinside.com 2019 - 2024. All rights reserved.