我对涉及reCAPTCHA的php感到困惑

时间:2018-08-27 03:08:46

标签: javascript php recaptcha

我正在尝试制作一个包含reCAPTCHA的非常基本的网站。我已经获得了我的站点密钥和秘密密钥,并且到目前为止还没有完成2个教程的学习

网站的目标是使用表格从用户那里获得一个数字作为输入,并在reCAPTCHA成功并且按下提交按钮后显示一个字符串。

到目前为止,这是我的代码

<!DOCTYPE HTML>
<html> <!-- template-->
<head>
  <title>template</title>

  <script src="lib/jquery-2.1.4.min.js"></script> 
  <script src='https://www.google.com/recaptcha/api.js'></script>


</head> 

<body>

<form action="/verify.php" method="get">
  Number:<br>
  <input type="text" name="firstname"><br>
  <div class="g-recaptcha" data-sitekey="6LcKeGwUAAAAAOdDqu2CzJxZdgYUXEUEPQKZBOtn"></div>
  <input type="submit" value="Submit" />

</form>

</body>
</html>

这是我的PHP

<html>
<body>

The number is <?php echo $_GET["number"]; ?><br>

<?php 
  if ($_GET["number"] == 42)
  echo "42 is the right answer!";
?>

</body>
</html>

到目前为止,该网站工作正常……除了我不知道如何添加reCAPTCHA代码,而Google文档使我困惑,因为我对php的了解很少。

非常感谢任何代码示例或指向简单文档的链接。这是我关于stackoverflow的第一篇文章...我希望我能遵守足够的规则

2 个答案:

答案 0 :(得分:0)

这将是您的verify.php

$post_data = http_build_query(
    array(
        'secret' => CAPTCHA_SECRET, //as provided from google
        'response' => $_POST['g-recaptcha-response'],
        'remoteip' => $_SERVER['REMOTE_ADDR']
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $post_data
    )
);
$context  = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
if ($result->success) {
//success,
echo $_GET["firstname"]; //your input field name was 'firstname' not 'number'

}else{
echo 'we think you are a bot';
//fail

}

答案 1 :(得分:0)

我建议将您的HTML代码更改为此:

            

  <form method="post" action="verify.php">
    Number:<br> 
    <input type="text" name="number"><br>
    <?php
      require_once('recaptchalib.php');
      $publickey = "your_public_key"; // you got this from the signup page
      echo recaptcha_get_html($publickey);
    ?>
    <input type="submit" />
  </form>

  <!-- more of your HTML content -->
</body>

并在 verify.php 中添加以下内容:

<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
                            $_SERVER["REMOTE_ADDR"],
                            $_POST["recaptcha_challenge_field"],
                            $_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
  // What happens when the CAPTCHA was entered incorrectly
  die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
     "(reCAPTCHA said: " . $resp->error . ")");
} else {
  // Your code here to handle a successful verification
  if (isset($_POST['number']) && $_POST['number'] == '42') {
    echo "42 is the right answer!";
  }
}
?>