Bonjour à tous,

Débutant en php j'ai suivi un tutoriel pour mettre en place un recaptcha v3 dans la rubrique "commentaires" de mon site.
Je l'avais fait auparavant pour ma rubrique "contact" avec un autre tuto
J'ai bien la pastille qui apparait mais j'ai l'impression d'avoir fait ça un peu de manière aléatoire, j'ai été surpris déjà de voir la pastille.

Comment être sur que ça fonctionne réellement ?

Je vous montre mon code pour la rubrique "commentaires" et "contact"

Pour la rubrique "commentaires" :

Code html : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
 <!-- Début Commentaires -->
          <form action="add_comment.php" id="comment_form" method="POST">
            <div class="fields">
              <div class="field half">
                <label for="name">Pseudo</label>
                <input
                  type="text"
                  name="comment_name"
                  id="comment_name"
                  required
                />
              </div>
              <div class="field half">
                <label for="email">Email</label>
                <input type="email" name="email" id="email" required />
              </div>
              <div class="field">
                <label for="message">Message</label>
                <textarea
                  name="comment_content"
                  id="comment_content"
                  rows="4"
                  required
                ></textarea>
                <span id="comment_message"></span>
                <!--Ton message a bien été envoyé-->
                <!--Une «alerte» div cachée ci-dessous pour afficher le message reçu du serveur une fois le formulaire soumis-->
                <div id="alert2"></div>
                <!--recaptcha cachée ci-dessous-->
                <input
                  type="hidden"
                  class="grecaptcha-badge"
                  id="recaptchaResponse-com"
                  name="recaptcha-response"
                />
                <input
                  type="hidden"
                  name="comment_id"
                  id="comment_id"
                  value="0"
                />
                <!--Fin alerte-->
              </div>
            </div>
            <ul class="actions">
              <li>
                <button class="primary" type="submit">Envoyer</button>
              </li>
              <li>
                <input type="reset" value="Effacer" />
              </li>
            </ul>
 
          </form>
 
          <!--recaptcha-->
          <script src="https://www.google.com/recaptcha/api.js?render=***p"></script>
          <script>
            grecaptcha.ready(function () {
              grecaptcha
                .execute("***", {
                  action: "homepage",
                })
                .then(function (token) {
                  document.getElementById(
                    "recaptchaResponse-com"
                  ).value = token;
                });
            });
          </script>
 
          <div id="display_comment"></div>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
          <script>
            $(document).ready(function () {
              //quand le DOM est là, on sélectionne les éléments avec lesquels on va travailler
              //c'est mieux de le faire une fois au début, pour des questions de perf
              //mais surtout pour éviter d'avoir à faire un gros ctrl + r pour changer les sélecteurs.
              const $comment_form = $("#comment_form");
              const $comment_message = $("#comment_message");
              const $display_comment = $("#display_comment");
              $comment_form.on("submit", function (event) {
                event.preventDefault();
                const form_data = $comment_form.serialize();
                $.ajax({
                  url: "add_comment.php",
                  method: "POST",
                  data: form_data,
                  dataType: "JSON",
                  success: function (data) {
                    if (data.error !== "") {
                      $comment_form[0].reset();
                      $comment_message.html(data.error);
                      //un formulaire (élément) contient tous ses inputs
                      //c'est rangé par nom
                      $comment_form[0].comment_id.value = "0";
                      load_comment();
                    }
                  },
                });
              });
              reload();
              //////////////////////////////////
              function load_comment() {
                $.ajax({
                  url: "fetch_comment.php",
                  //POST pour envoyer des données, et GET pour obtenir des données
                  method: "POST",
                  success: function (data) {
                    $display_comment.html(data);
                    $(".reply").on("click", function () {
                      $comment_form[0].comment_id.value = $(this).attr("id");
                      $comment_form[0].comment_name.focus();
                    });
                  },
                });
              }
 
              function reload() {
                load_comment();
                setTimeout(reload, 1000);
              }
            });
          </script>
 
          <!-- Fin Commentaires -->

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
 
//add_comment.php
 
$connect = new PDO('***');
 
$error = '';
$comment_name = '';
$comment_content = '';
$email = '';
 
 
// Début recaptcha
 
// On vérifie si le champ "recaptcha-response" contient une valeur
if(empty($_POST['recaptcha-response'])){
    header('Location: index.html');
    die();
}else{
 
// On prépare l'URL
$url = "https://www.google.com/recaptcha/api/siteverify?secret=***&response={$_POST['recaptcha-response']}";
 
// On vérifie si curl est installé
if(function_exists('curl_version')){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($curl);
}else{
    // On utilisera file_get_contents
    $response = file_get_contents($url);
}
// On vérifie qu'on a une réponse
if(empty($response) || is_null($response)){
    header('Location: index.html');
    die();
}else{
    $data = json_decode($response);
    if($data->success){
        // Google a répondu avec un succès
        // On traite le formulaire
    }else{
        header('Location: index.html');
        die();
    }
}
 // Fin recaptcha
 
 
 
if(empty($_POST["comment_name"]))
{
 $error .= '<p class="text-danger"></p>';
}
else
{
 $comment_name = $_POST["comment_name"];
}
 
if(empty($_POST["comment_content"]))
{
 $error .= '<p class="text-danger"></p>';
}
else
{
 $comment_content = $_POST["comment_content"];
}
 
if(empty($_POST["email"]))
{
 $error .= '<p class="text-danger"></p>';
}
else
{
 $email = $_POST["email"];
}
 
if($error == '')
{
 $query = "
 INSERT INTO tbl_comment 
 (parent_comment_id, comment, comment_sender_name, email) 
 VALUES (:parent_comment_id, :comment, :comment_sender_name, :email)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':parent_comment_id' => $_POST["comment_id"],
   ':comment'    => $comment_content,
   ':comment_sender_name' => $comment_name,
   ':email' => $_POST["email"]
  )
 );
 $error = '<label class="validation">Ton message a bien été envoyé !</label>';
}
else{
    header('Location: index.html');// Fin recaptcha-2
    die();
}
}
 
$data = array(
 'error'  => $error
);
 
echo json_encode($data);
 
?>
Pour la rubrique "contact" :

Code html : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!-- Contact -->
        <article class="color-c" id="contact">
          <h2 class="major">Contact</h2>
          <form id="contact-form" method="post">
            <div class="fields">
              <div class="field half">
                <label for="name">Nom</label>
                <input type="text" name="name" id="name" required />
              </div>
              <div class="field half">
                <label for="email">Email</label>
                <input type="email" name="email" required />
              </div>
              <div class="field">
                <label for="message">Message</label>
                <textarea
                  name="message"
                  id="message"
                  rows="4"
                  required
                ></textarea>
                <!--Une «alerte» div cachée ci-dessous pour afficher le message reçu du serveur une fois le formulaire soumis-->
                <div id="alert"></div>
                <input
                  type="hidden"
                  name="recaptcha_response"
                  id="recaptchaResponse"
                />
                <!--Fin alerte-->
              </div>
            </div>
            <ul class="actions">
              <li>
                <button class="primary" type="submit">Envoyer</button>
              </li>
              <li>
                <input type="reset" value="Effacer" />
              </li>
            </ul>
 
          </form>
        </article>
 <!-- Recaptcha contact Début -->
    <script
      async
      src="https://www.google.com/recaptcha/api.js?render=***"
    ></script>
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Recaptcha contact Fin -->


Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
 
 
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: ***';
 
$messageHTML = "<html>
      <head>
       <title>Nouveau message !</title>
      </head>
      <body>
       <p>Message provenant de *** :</p>
       <ul>
          <li><b>Nom : </b>".strip_tags($name)."</li>
          <li><b>Email : </b>".strip_tags($email)."</li>
          <li><b>Message : </b>".nl2br(strip_tags($message))."</li>
       </ul>
      </body>
     </html>
     ";
 
$to = '***';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
$header = "From:***\r\n";
$header.= "MIME-Version: 1.0\r\n";
$header.= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$header.= "X-Priority: 1\r\n";
 
$status = mail($to, $subject, $messageHTML, $header);
 
 
// Server side validation
if($status) { 
    echo 'Ton message a bien été envoyé !';
} else { 
    echo 'OOPS ! Ton message ne veut pas partir.. Réessaie !'; 
}
 
    if ($_POST['submit']) {
        if (mail ($to, $body, $from)) { 
            echo '<p>Ton message a bien été envoyé !</p>';
        } else { 
            echo '<p>OOPS ! Ton message ne veut pas partir.. Réessaie !</p>'; 
        }
    }
// DEBUT FREE MOBILE SMS
 
// inclure ici le fichier de la classe
require_once "FreeMobileSMS.php";
 
$sms = new FreeMobileSMS();
 
/**
* configure l'ID utilisateur et la clé disponible dans
* le compte Free Mobile après avoir activé l'option.
*/
$sms->setKey("***")
    ->setUser("***");
 
try {
    // envoi d'un message
    $sms->send(html_entity_decode(strip_tags("$messageHTML")));
} catch (Exception $e) {
    // le monde n'est pas parfait, il y aura
    // peut-être des erreurs.
    $this->Session->setFlash("Erreur sur envoi de SMS: (".$e->getCode().") ".$e->getMessage(), 'danger');
}
 
// FIN FREE MOBILE SMS
 
if($status) {
    // Build POST request to get the reCAPTCHA v3 score from Google
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_secret = '***'; // Insert your secret key here
    $recaptcha_response = $_POST['recaptcha_response'];
 
    // Make and decode POST request
    $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
    $recaptcha = json_decode($recaptcha);
 
    // Take action based on the score returned
    if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'contact') {
        // This is a human. Insert the message into database OR send a mail
        $success_output = "Ton message a bien été envoyé !";
    } else {
        // Score less than 0.5 indicates suspicious activity. Return an error
        $error_output = "OOPS ! Ton message ne veut pas partir.. Réessaie !";
    }
} else {
    // Server side validation failed
    $error_output = "Veuillez remplir tous les champs obligatoires";
}
 
 
 
?>

Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    $('#contact-form').submit(function(event) {
        event.preventDefault(); // Prevent direct form submission
        $('#alert').text('Envoi en cours...').fadeIn(0); // Display "Processing" to let the user know that the form is being submitted
        grecaptcha.ready(function () {// Clef REcaptcha site ci dessous   
         grecaptcha.execute('***', { action: 'contact' }).then(function (token) {
                var recaptchaResponse = document.getElementById('recaptchaResponse');
                recaptchaResponse.value = token;
                // Make the Ajax call here
                $.ajax({
                    url: 'contact.php',
                    type: 'post',
                    data: $('#contact-form').serialize(),
                    dataType: 'json',
                    success: function( _response ){
                        // The Ajax request is a success. _response is a JSON object
                        var error = _response.error;
                        var success = _response.success;
                        if(error != "") {
                            // In case of error, display it to user
                            $('#alert').html(error);
                        }
                        else {
                            // In case of success, display it to user and remove the submit button
                            $('#alert').html(success);
                            $('#btn #delicious-btn #mt-30').remove();
                            $('#form-control')[0].reset();
 
                        }
 
                    },
                    error: function(jqXhr, json, errorThrown){
                        // In case of Ajax error too, display the result
                        var error = jqXhr.responseText;
                        $('#alert').html(error);
                        $('#contact-form')[0].reset();
                    }
 
                });
            });
        });
    });
Je suis vraiment désolé pour la masse de code, je ne voyais pas trop comment faire plus simple