简体   繁体   English

recaptcha为我在php中的登录无法正常工作

[英]recaptcha for my login in php not working

I have a website which is like the url http://molugu.com/demo/vendor/register.php 我有一个网址为http://molugu.com/demo/vendor/register.php的网站

My register.php is below: 我的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> 

Its a register page, with recaptcha from google. 它是一个注册页面,来自Google的Recaptcha。 I have added the secret key from google which I got for my domain https://molugu.com . 我已经添加了我从我的域https://molugu.com获得的google的密钥。 But when I am loading my registeration page, its showing the following error: 但是,当我加载我的注册页面时,它显示以下错误:

ERROR for site owner: Invalid site key 网站所有者错误:网站密钥无效

The code for recaptcha is as follows: 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; } } ?> 

Can anyone please tell me what could be the problem in recaptcha? 谁能告诉我重新验证可能是什么问题?

Process for use reCAPTCHA 使用过程reCAPTCHA

First create Google reCAPTCHA account 首先创建Google reCAPTCHA帐户

After that copy credentials and put them into code after that your reCAPTCHA will work successfully. 之后,复制凭据并将其放入代码中,之后您的reCAPTCHA将成功运行。

You can use Using reCAPTCHA with PHP tutorial to successfully configure captcha using PHP 您可以使用“ 将reCAPTCHA与PHP结合使用”教程来使用PHP成功配置验证码

recaptchalib.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 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 

?>

You have the http version of website 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. 你有网站的HTTP版本http://molugu.com/demo/vendor/register.php ,并且您已经注册验证码以https版本: https://molugu.com ,你需要指定有两个版本。 在此处输入图片说明

Also you need to use "The reCAPTCHA PHP Library" provided by Google reCaptcha. 另外,您还需要使用Google reCaptcha提供的“ reCAPTCHA PHP库”。 Find out more here: Using reCAPTCHA with PHP 在此处了解更多信息: 将reCAPTCHA与PHP结合使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM