我在 php 中登录的验证码无法正常工作

recaptcha for my login in php not working

我有一个类似于 url http://molugu.com/demo/vendor/register.php

的网站

我的register.php如下:

<?php
require_once('connect.php');
include('config.php');
include('recaptchalib.php');
$response = null;
$reCaptcha = new ReCaptcha($secret);
if(isset($_POST) & !empty($_POST)){

 if($_POST['g-recaptcha-response']){
  $response = $reCaptcha->verifyResponse(
    $_SERVER['REMOTE_ADDR'],
    $_POST['g-recaptcha-response']
   );

 }

 if($response != null && $response->success){
  $username = mysqli_real_escape_string($connection, $_POST['username']);
  $verification_key = md5($username);
  $email = mysqli_real_escape_string($connection, $_POST['email']);
  $password = md5($_POST['password']);
  $passwordagain = md5($_POST['passwordagain']);
  if($password == $passwordagain){
   $fmsg = "";
   
   $usernamesql = "SELECT * FROM `usermanagement` WHERE username='$username'";
   $usernameres = mysqli_query($connection, $usernamesql);
   $count = mysqli_num_rows($usernameres);
   if($count == 1){
    $fmsg .= "Username exists in Database, please try different user name";
   }

   $emailsql = "SELECT * FROM `usermanagement` WHERE email='$email'";
   $emailres = mysqli_query($connection, $emailsql);
   $emailcount = mysqli_num_rows($emailres);
   if($emailcount == 1){
    $fmsg .= "Email exists in Database, please reset your password";
   }


   echo $sql = "INSERT INTO `usermanagement` (username, email, password, verification_key) VALUES ('$username', '$email', '$password', '$verification_key')";
   $result = mysqli_query($connection, $sql);
   if($result){
    $smsg = "User Registered succesfully";
    $id = mysqli_insert_id($connection);
     require 'PHPMailer/PHPMailerAutoload.php';

     $mail = new PHPMailer;

     $mail->isSMTP();
     $mail->Host = $smtphost;
     $mail->SMTPAuth = true;
     $mail->Username = $smtpuser;
     $mail->Password = $smtppass;
     $mail->SMTPSecure = 'ssl';
     $mail->Port = 465;

     $mail->setFrom('info@pixelw3.com', 'PixelW3 Technologies');
     $mail->addAddress('vivek@codingcyber.com', 'Vivek Vengala'); 

     $mail->Subject = 'Verify Your Email';
     $mail->Body    = "http://localhost/user-management/verify.php?key=$verification_key&id=$id";
     $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

     if(!$mail->send()) {
         echo 'Message could not be sent.';
         echo 'Mailer Error: ' . $mail->ErrorInfo;
     } else {
         echo 'Message has been sent';
     }

   }else{
    $fmsg .= "Failed to register user";
   }
  }else{
   $fmsg = "Password not matching";
  }
 }
}
?>
<html>
<head>
<title>User Registration Script in PHP & MySQL</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >

<link rel="stylesheet" href="styles.css" >
<script   src="https://code.jquery.com/jquery-3.1.1.js" ></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
 $('#usernameLoading').hide();
 $('#username').keyup(function(){
   $('#usernameLoading').show();
      $.post("check.php", {
        username: $('#username').val()
      }, function(response){
        $('#usernameResult').fadeOut();
        setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
      });
     return false;
 });
});

function finishAjax(id, response) {
  $('#usernameLoading').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
} //finishAjax
</script>

</head>
<body>
 <div class="container">
      <?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
      <?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
      <form class="form-signin" method="POST">
        <h2 class="form-signin-heading">Please Register</h2>
        <div class="input-group">
    <span class="input-group-addon" id="basic-addon1">@</span>
    <input type="text" name="username" id="username" class="form-control" placeholder="Username" value="<?php if(isset($username) & !empty($username)){ echo $username; } ?>" required>
   <span id="usernameLoading" class="input-group-addon"><img src="loading.gif" height="30px" alt="Ajax Indicator" /></span>
  </div>
  <span id="usernameResult"></span> 
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" value="<?php if(isset($email) & !empty($username)){ echo $email; } ?>" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <label for="inputPassword" class="sr-only">Password Again</label>
        <input type="password" name="passwordagain" id="inputPassword" class="form-control" placeholder="Password Again" required>
        <div class="g-recaptcha" data-sitekey="6LeuQwkUAAAAAPrlzSQ-xxxxxxxxxx"></div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
        <a class="btn btn-lg btn-primary btn-block" href="login.php">Login</a>
      </form>
</div>
<?php require_once('credits.php'); ?>
</body>
</html>

这是一个注册页面,带有 google 的重新验证码。我已经从 google 添加了我为我的域 https://molugu.com 获得的密钥。但是当我加载我的注册页面时,它显示以下错误:

ERROR for site owner: Invalid site key

recaptcha的代码如下:

<?php
class ReCaptchaResponse
{
    public $success;
    public $errorCodes;
}
class ReCaptcha
{
    private static $_signupUrl = "https://www.google.com/recaptcha/admin";
    private static $_siteVerifyUrl =
        "https://www.google.com/recaptcha/api/siteverify?";
    private $_secret;
    private static $_version = "php_1.0";
    /**
     * Constructor.
     *
     * @param string $secret shared secret between site and ReCAPTCHA server.
     */
    function ReCaptcha($secret)
    {
        if ($secret == null || $secret == "") {
            die("To use reCAPTCHA you must get an API key from <a href='"
                . self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
        }
        $this->_secret=$secret;
    }
    /**
     * Encodes the given data into a query string format.
     *
     * @param array $data array of string elements to be encoded.
     *
     * @return string - encoded request.
     */
    private function _encodeQS($data)
    {
        $req = "";
        foreach ($data as $key => $value) {
            $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
        }
        // Cut the last '&'
        $req=substr($req, 0, strlen($req)-1);
        return $req;
    }
    /**
     * Submits an HTTP GET to a reCAPTCHA server.
     *
     * @param string $path url path to recaptcha server.
     * @param array  $data array of parameters to be sent.
     *
     * @return array response
     */
    private function _submitHTTPGet($path, $data)
    {
        $req = $this->_encodeQS($data);
        $response = file_get_contents($path . $req);
        return $response;
    }
    /**
     * Calls the reCAPTCHA siteverify API to verify whether the user passes
     * CAPTCHA test.
     *
     * @param string $remoteIp   IP address of end user.
     * @param string $response   response string from recaptcha verification.
     *
     * @return ReCaptchaResponse
     */
    public function verifyResponse($remoteIp, $response)
    {
        // Discard empty solution submissions
        if ($response == null || strlen($response) == 0) {
            $recaptchaResponse = new ReCaptchaResponse();
            $recaptchaResponse->success = false;
            $recaptchaResponse->errorCodes = 'missing-input';
            return $recaptchaResponse;
        }
        $getResponse = $this->_submitHttpGet(
            self::$_siteVerifyUrl,
            array (
                'secret' => $this->_secret,
                'remoteip' => $remoteIp,
                'v' => self::$_version,
                'response' => $response
            )
        );
        $answers = json_decode($getResponse, true);
        $recaptchaResponse = new ReCaptchaResponse();
        if (trim($answers ['success']) == true) {
            $recaptchaResponse->success = true;
        } else {
            $recaptchaResponse->success = false;
            $recaptchaResponse->errorCodes = $answers [error-codes];
        }
        return $recaptchaResponse;
    }
}
?>

谁能告诉我 recaptcha 中的问题是什么?

reCAPTCHA 使用流程

首先创建Google reCAPTCHA账户

复制凭据并将其放入代码之后,您的 reCAPTCHA 将成功运行。

You can use Using reCAPTCHA with PHP tutorial to successfully configure captcha using PHP

recaptchalib.php

<?php
# PHPreCAPTCHA v0.1
# GNU General Public License v3.0
# This is a PHP library for Google's reCAPTCHA 2.0
# Created by Martin Georgiev, geeorgiev[at]gmail.com
# Web: www.viziongames.com
/**
 * recaptchalib class
 */
class recaptchalib
{
    /**
     * @var string
     */
    protected $secret;
    /**
     * @var string
     */
    protected $response;
    /**
     * @var string
     */
    protected $URL;
    function __construct($secret, $response)
    {
        $this->secret = $secret;
        $this->response = $response;
        $this->URL = 'https://www.google.com/recaptcha/api/siteverify';
    }
    /**
     * Validating reCAPTCHA response
     * Response is collected from $_POST["g-recaptcha-response"]
     *
     * @param string $response
     * @return booleans
     */
    public function isValid()
    {
        $data = array(
            'secret' => $this->secret,
            'response' => $this->response
        );
        $options = array(
            'http' => array (
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $verify = file_get_contents($this->URL, false, $context);
        return $this->fromJson($verify);
    }
    /**
     * Return response from the expected JSON returned by the service.
     *
     * @param string $json
     * @return string
     */
    public function fromJson($json)
    {
        $responseData = json_decode($json, true);
        if (!$responseData) {
            return false;
        }
        $hostname = isset($responseData['hostname']) ? $responseData['hostname'] : null;
        if (isset($responseData['success']) && $responseData['success'] == true) {
            return $responseData['success'];
        }
        if (isset($responseData['error-codes']) && is_array($responseData['error-codes'])) {
            return false;
        }
        return false;
    }
}

Register.php

<?php

    require_once('recaptchalib.php');
    $secretkey = "6LeOsq0UAAAAHHIg61k8Rq4RcOK1b933JtnmvAK"; //add your secret key here
    $response = $_POST["g-recaptcha-response"];
    $verify = new recaptchalib($secretkey, $response);

    if ($verify->isValid() == false) {
        echo "Captcha Not Matched";
        die();
    }

// and then add rest of code here 

?>

您有http版本的网站http://molugu.com/demo/vendor/register.php, and you have registered reCaptcha with https version: https://molugu.com, you need to specify both versions there.

您还需要使用 Google reCaptcha 提供的 "The reCAPTCHA PHP Library"。 在此处了解更多信息:Using reCAPTCHA with PHP