首页 > 解决方案 > 在同一页面上显示 Google reCAPTCHA 响应

问题描述

我正在建立一个带有联系表格的网站,我希望能够在同一页面上显示 Google reCAPTCHA 响应(例如“消息发送成功”或“无效的 reCAPTCHA。再试一次。”),而不是将其转发到我的其他 .php 文件。

我已经通过 localhost 进行了尝试,并且可以通过其他 .php 文件获得响应,但它使您远离主页,这是我不想要的。

如果我在主网站代码中有联系表单代码,它确实会按照我的意愿行事,但我宁愿有两个单独的文件 & do <form action="assets/php/form.php" method="post">.

我尝试通过 Paint 来说明这一点(我不是艺术家)。

我是个新手,大约 5/6 年前我做了一些基本的 HTML/CSS,但从那以后就没有真正编码过。

这是到目前为止的代码:

index.php(只是表单)

<form action="assets/php/form.php" method="post">
    <div class="fields">
        <div class="field half">
            <label for="name">Name</label>
            <input type="text" name="name" id="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="message" id="message" rows="5" required></textarea>
        </div>
    </div>

<div class="g-recaptcha" data-sitekey="My Site Key"></div>

<br/>

    <ul class="actions">
        <li><input type="submit" name="submit" value="Send Message" class="submit-btn"></li>
    </ul>
</form>

表单.php

<?php
    
    if (isset($_POST['submit'])) 
    {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];

        $mailTo = "email@mydomain.co.uk";
        $headers = "From: ".$email;
        $txt = "You have received an email from ".$name.".\n\n".$message;

        $secretKey = "My Secret Key";
        $responseKey = $_POST['g-recaptcha-response'];
        $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";

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

        if ($response->success) {
            mail($mailTo, $email, $txt, $headers);
            header("Location: http://localhost/website/index.php?formsent");
            echo "Thanks for sending us a message, it was sent successfully. We will get back to you as soon as possible.";
        } 
        
        else {
            echo "Invalid reCAPTCHA. Please try again.";
        }
        
    }
?>

希望这是足以帮助某人的信息。谢谢。

标签: phphtmlrecaptcha

解决方案


推荐阅读