如何将reCaptchaV3集成到联系表中?

首先,我是一个狂热的爱好者,但没有任何专业知识,因此我在编码方面有了一些基础知识。 我正在尝试将reCaptcha V3集成到我现有的联系表中。 但是我不知道是否做对了。我一直像疯子一样谷歌搜索,但是所有的“操作方法”都在做些不同的事情。我昨天使用以下示例添加了该示例:https://code.tutsplus.com/tutorials/example-of-how-to-add-google-recaptcha-v3-to-a-php-form--cms-33752,并在分析中获得了0.9分的成绩,但我仍然不太确定其能否正常工作。

我用此https://recaptcha-demo.appspot.com/recaptcha-v3-request-scores.php测试了我的分数,结果是0.9 我尝试在自己的网站上将所需的分数更改为1.0,但提交仍然成功。

这是我添加来加载reCaptcha的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<link rel="stylesheet" href="styles/contact.css">
<link rel="stylesheet" href="styles/layout.css">
<link rel="stylesheet" href="validate/css/style.css">
                                                                <!----- SITE KEY REPCAPTCHA ----->
<script src="https://www.google.com/recaptcha/api.js?render=*****"></script>
<script>
    grecaptcha.ready(function() {
    grecaptcha.execute('******',{action: 'contact'}).then(function(token) {
       $('#contact').prepend('<input type="hidden" name="token" value="' + token + '">');
       $('#contact').prepend('<input type="hidden" name="action" value="contact">');
       $('#contact').unbind('submit').submit();
    });
});
</script>

$('#contact')部分在firefox控制台中给出了一个错误:ReferenceError:未定义$。但是我发现其他代码也被使用了,所以我想它可以正常工作吗?

这是我完整的联系表:

                <h1></h1>
                <br />
                <h2></h2>
                <h2></h2>
                    <?php
                        //init variables
                        $cf = array();
                        $sr = false;

                    if(isset($_SESSION['cf_returndata'])){
                        $cf = $_SESSION['cf_returndata'];
                        $sr = true;
                    }
                    ?>
                <ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
                    <li id="info">Er zijn wat problemen met je bericht:</li>
                        <?php 
                            if(isset($cf['errors']) && count($cf['errors']) > 0) :
                            foreach($cf['errors'] as $error) :
                        ?>
                    <li><?php echo $error ?></li>
                        <?php
                            endforeach;
                            endif;
                        ?>
                </ul>
                    <p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'visible' : ''; ?>">Bedankt voor je bericht!<br />Je hoort zo snel mogelijk van ons!</p>
                <form id="contact" method="post" action="validate/process.php">
                    <label for="name">Naam: <span class="required">*</span></label>
                    <input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="naam" />

                    <label for="email">Email: <span class="required">*</span></label>
                    <input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="naam@voorbeeld.nl"  />

                    <label for="telephone">Telefoon:</label>
                    <input type="tel" id="telephone" name="telephone"  placeholder="0612345678" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />

                    <label for="enquiry">Onderwerp: <span class="required">*</span></label>
                    <select required id="enquiry" name="enquiry">
                        <option value="" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Maak keuze') ? "selected='selected'" : '' ?>>Maak een keuze..</option>
                        <option value="steppen" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Steppen') ? "selected='selected'" : '' ?>>Steppen</option>
                        <option value="walks" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Walks') ? "selected='selected'" : '' ?>>Walks</option>
                        <option value="sessions" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Privatewalks') ? "selected='selected'" : '' ?>>Persoonlijke begeleiding (Private walks)</option>
                        <option value="sessions" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Events') ? "selected='selected'" : '' ?>>Events</option>
                        <option value="foto" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Foto') ? "selected='selected'" : '' ?>>Foto's opvragen</option>
                        <option value="website" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Website') ? "selected='selected'" : '' ?>>Website</option>
                        <option value="overig" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Overig...') ? "selected='selected'" : '' ?>>Overig...</option>
                    </select>

                    <label for="message">bericht: <span class="required">*</span></label>
                    <textarea id="message" name="message" placeholder="Minimaal 20 karakters"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
                    <input type="submit" value="Versturen" id="submit-button" />
                    <p id="req-field-desc">Velden met een <span class="required">*</span> zijn verplicht.</p>
                    <br />

               </form>
                <?php unset($_SESSION['cf_returndata']); ?>
                </div>

这是我的表单验证文件:

if( isset($_POST) ){

    //form validation vars
    $formok = true;
    $errors = array();

    //sumbission data
    $ipaddress = $_SERVER['REMOTE_ADDR'];
    $date = date('d/m/Y');
    $time = date('H:i:s');

    //form data
    $name = $_POST['name']; 
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $enquiry = $_POST['enquiry'];
    $message = $_POST['message'];

    //validate form data

    //validate name is not empty
    if(empty($name)){
        $formok = false;
        $errors[] = "U heeft geen naam ingevuld";
    } elseif(!preg_match("/^[a-zA-Z ]*$/",$name)) {
        $formok = false;
        $errors[] = "Uw naam mag alleen letters en/of spaties bevatten";
    }

    //validate email address is not empty
    if(empty($email)){
        $formok = false;
        $errors[] = "U heeft geen email adres ingevuld";
    //validate email address is valid
    } elseif(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
        $formok = false;
        $errors[] = "U heeft geen geldig email adres ingevuld";
    }

    //validate message is not empty
    if(empty($message)){
        $formok = false;
        $errors[] = "U heeft geen bericht ingevuld";
    }
    //validate message is greater than 20 charcters
    elseif(strlen($message) < 20){
        $formok = false;
        $errors[] = "Uw bericht moet minimaal 20 karakters bevatten";
    }

    // reCaptcha V3 stuff
        define("RECAPTCHA_V3_SECRET_KEY",'*****');
        $token = $_POST['token'];
        $action = $_POST['action'];

    // call curl to POST request
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query(array('secret' => RECAPTCHA_V3_SECRET_KEY,'response' => $token)));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $response = curl_exec($ch);
        curl_close($ch);
        $arrResponse = json_decode($response,true);

    // verify the response
        if($arrResponse["success"] == '1' && $arrResponse["action"] == $action && $arrResponse["score"] >= 0.5) {
            // valid submission
            // go ahead and do necessary stuff
        } else {
            $errors[] = "reCaptcha you are a bot";
            // spam submission
            // show error message
        }

    //send email if all is ok
    if($formok){
        $headers = "From: $email" . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        $emailbody = "";

        mail("",'',$emailbody,$headers);

    }
    //what we need to return back to our form
    $returndata = array(
        'posted_form_data' => array(
            'name' => $name,'email' => $email,'telephone' => $telephone,'enquiry' => $enquiry,'message' => $message
        ),'form_ok' => $formok,'errors' => $errors
    );


    //if this is not an ajax request
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
        //set session variables
        session_start();
        $_SESSION['cf_returndata'] = $returndata;

        //redirect back to form
        header('location: ' . $_SERVER['HTTP_REFERER']);
    }
}

我尝试添加$ formok = false;在“验证响应”部分:

        if($arrResponse["success"] == '1' && $arrResponse["action"] == $action && $arrResponse["score"] >= 0.5) {
            // valid submission
            // go ahead and do necessary stuff
        } else {
    --------->      $formok = false;
                        $errors[] = "reCaptcha you are a bot";
            // spam submission
            // show error message
        }

但这会导致始终无法提交。

我希望有人能阐明我的表现。这样,应该行吗?还是我犯了一些错误?

谢谢!

shensheng1981 回答:如何将reCaptchaV3集成到联系表中?

我遵循了本教程,对我来说效果很好。 https://stevencotterill.com/articles/adding-google-recaptcha-v3-to-a-php-form

只需尝试看看您的代码是否有问题。

您应该在HTML中包含jQuery,以使$正常工作

The $('#contact') part give's an error in firefox console: ReferenceError: $ is not defined. But i found other pieces of code were this is also used so i guess it just works?
本文链接:https://www.f2er.com/3133088.html

大家都在问