Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用ajax和PHP以简单形式登录_Javascript_Php_Jquery_Ajax_Recaptcha - Fatal编程技术网

Javascript 使用ajax和PHP以简单形式登录

Javascript 使用ajax和PHP以简单形式登录,javascript,php,jquery,ajax,recaptcha,Javascript,Php,Jquery,Ajax,Recaptcha,我用一个按钮提交和电子邮件输入来进行登录。但是当我想添加recaptcha谷歌v2时。我发现了很多问题。 require_once 'includes/main.php'; /*-------------------------------------------------- Handle visits with a login token. If it is valid, log the person in. -------------------------------

我用一个按钮提交和电子邮件输入来进行登录。但是当我想添加
recaptcha
谷歌v2时。我发现了很多问题。
require_once 'includes/main.php';


/*--------------------------------------------------
    Handle visits with a login token. If it is
    valid, log the person in.
---------------------------------------------------*/


if(isset($_GET['tkn'])){

    // Is this a valid login token?
    $user = User::findByToken($_GET['tkn']);

    if($user){

        // Yes! Login the user and redirect to the protected page.

        $user->login();
        redirect('protected.php');
    }

    // Invalid token. Redirect back to the login form.
    redirect('index.php');
}



/*--------------------------------------------------
    Handle logging out of the system. The logout
    link in protected.php leads here.
---------------------------------------------------*/


if(isset($_GET['logout'])){

    $user = new User();

    if($user->loggedIn()){
        $user->logout();
    }

    redirect('index.php');
}


/*--------------------------------------------------
    Don't show the login page to already 
    logged-in users.
---------------------------------------------------*/


$user = new User();

if($user->loggedIn()){
    redirect('protected.php');
}



/*--------------------------------------------------
    Handle submitting the login form via AJAX
---------------------------------------------------*/


try{

    if(!empty($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

        // Output a JSON header

        header('Content-type: application/json');

        // Is the email address valid?

        if(!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            throw new Exception('Please enter a valid email.');
        }

        // This will throw an exception if the person is above 
        // the allowed login attempt limits (see functions.php for more):
        rate_limit($_SERVER['REMOTE_ADDR']);

        // Record this login attempt
        rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);

        // Send the message to the user

        $message = '';
        $email = $_POST['email'];
        $subject = 'Your Login Link';

        if(!User::exists($email)){
            $subject = "Thank You For Registering!";
            $message = "Thank you for registering at our site!\n\n";
        }

        // Attempt to login or register the person
        $user = User::loginOrRegister($_POST['email']);


        $message.= "You can login from this URL:\n";
        $message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

        $message.= "The link is going expire automatically after 10 minutes.";

        $result = send_email($fromEmail, $_POST['email'], $subject, $message);

        if(!$result){
            throw new Exception("There was an error sending your email. Please try again.");
        }

        die(json_encode(array(
            'message' => 'Thank you! We\'ve sent a link to your inbox. Check your spam folder as well.'
        )));
    }
}
catch(Exception $e){

    die(json_encode(array(
        'error'=>1,
        'message' => $e->getMessage()
    )));
}

/*--------------------------------------------------
    Output the login form
---------------------------------------------------*/

?>

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8"/>
        <title></title>

        <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">

        <!-- The main CSS file -->
        <link href="assets/css/style.css" rel="stylesheet" />

        <!--[if lt IE 9]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <form id="login-register" method="post" action="index.php">

            <h1>Login or Register</h1>

            <input type="text" placeholder="your@email.com" name="email" autofocus />
            <p>Enter your email address above and we will send <br />you a login link.</p>

            <button type="submit">Login / Register</button>

            <span></span>

        </form>

        <footer>
            <a class="tz" href="#">#</a>
            <div id="tzine-actions"></div>
            <span class="close"></span>
        </footer>

        <!-- JavaScript Includes -->
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>
请帮帮我

index.php:
require_once 'includes/main.php';


/*--------------------------------------------------
    Handle visits with a login token. If it is
    valid, log the person in.
---------------------------------------------------*/


if(isset($_GET['tkn'])){

    // Is this a valid login token?
    $user = User::findByToken($_GET['tkn']);

    if($user){

        // Yes! Login the user and redirect to the protected page.

        $user->login();
        redirect('protected.php');
    }

    // Invalid token. Redirect back to the login form.
    redirect('index.php');
}



/*--------------------------------------------------
    Handle logging out of the system. The logout
    link in protected.php leads here.
---------------------------------------------------*/


if(isset($_GET['logout'])){

    $user = new User();

    if($user->loggedIn()){
        $user->logout();
    }

    redirect('index.php');
}


/*--------------------------------------------------
    Don't show the login page to already 
    logged-in users.
---------------------------------------------------*/


$user = new User();

if($user->loggedIn()){
    redirect('protected.php');
}



/*--------------------------------------------------
    Handle submitting the login form via AJAX
---------------------------------------------------*/


try{

    if(!empty($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

        // Output a JSON header

        header('Content-type: application/json');

        // Is the email address valid?

        if(!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            throw new Exception('Please enter a valid email.');
        }

        // This will throw an exception if the person is above 
        // the allowed login attempt limits (see functions.php for more):
        rate_limit($_SERVER['REMOTE_ADDR']);

        // Record this login attempt
        rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);

        // Send the message to the user

        $message = '';
        $email = $_POST['email'];
        $subject = 'Your Login Link';

        if(!User::exists($email)){
            $subject = "Thank You For Registering!";
            $message = "Thank you for registering at our site!\n\n";
        }

        // Attempt to login or register the person
        $user = User::loginOrRegister($_POST['email']);


        $message.= "You can login from this URL:\n";
        $message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

        $message.= "The link is going expire automatically after 10 minutes.";

        $result = send_email($fromEmail, $_POST['email'], $subject, $message);

        if(!$result){
            throw new Exception("There was an error sending your email. Please try again.");
        }

        die(json_encode(array(
            'message' => 'Thank you! We\'ve sent a link to your inbox. Check your spam folder as well.'
        )));
    }
}
catch(Exception $e){

    die(json_encode(array(
        'error'=>1,
        'message' => $e->getMessage()
    )));
}

/*--------------------------------------------------
    Output the login form
---------------------------------------------------*/

?>

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8"/>
        <title></title>

        <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">

        <!-- The main CSS file -->
        <link href="assets/css/style.css" rel="stylesheet" />

        <!--[if lt IE 9]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <form id="login-register" method="post" action="index.php">

            <h1>Login or Register</h1>

            <input type="text" placeholder="your@email.com" name="email" autofocus />
            <p>Enter your email address above and we will send <br />you a login link.</p>

            <button type="submit">Login / Register</button>

            <span></span>

        </form>

        <footer>
            <a class="tz" href="#">#</a>
            <div id="tzine-actions"></div>
            <span class="close"></span>
        </footer>

        <!-- JavaScript Includes -->
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>
一周前我试过了。但没有结果。我需要它为我的网站脚本。请帮助我,我不再知道我是否会继续脚本没有验证码

谢谢大家

我尝试将这段代码放在ajax中,但不起作用

$(function(){



var onloadCallback = function() {
    grecaptcha.render('recapptcha', {
    'sitekey' : '-------key----------'
  });
};
onloadCallback();


    var form = $('#login-register');

    form.on('submit', function(e){



  if(grecaptcha.getResponse() == "") {
    e.preventDefault();
    alert("You can't proceed!");
  } else {  



        if(form.is('.loading, .loggedIn')){
            return false;
        }

        var email = form.find('input').val(),
            messageHolder = form.find('span');

        e.preventDefault();

        $.post(this.action, {email: email}, function(m){

            if(m.error){
                form.addClass('error');
                messageHolder.text(m.message);
            }
            else{
                form.removeClass('error').addClass('loggedIn');
                messageHolder.text(m.message);
            }
        });

 }//recaptcha end tag

    });

    $(document).ajaxStart(function(){
        form.addClass('loading');
    });

    $(document).ajaxComplete(function(){
        form.removeClass('loading');
    });
});
我不知道如何使用ajax添加代码验证码

更新:

require_once 'includes/main.php';


/*--------------------------------------------------
    Handle visits with a login token. If it is
    valid, log the person in.
---------------------------------------------------*/


if(isset($_GET['tkn'])){

    // Is this a valid login token?
    $user = User::findByToken($_GET['tkn']);

    if($user){

        // Yes! Login the user and redirect to the protected page.

        $user->login();
        redirect('protected.php');
    }

    // Invalid token. Redirect back to the login form.
    redirect('index.php');
}



/*--------------------------------------------------
    Handle logging out of the system. The logout
    link in protected.php leads here.
---------------------------------------------------*/


if(isset($_GET['logout'])){

    $user = new User();

    if($user->loggedIn()){
        $user->logout();
    }

    redirect('index.php');
}


/*--------------------------------------------------
    Don't show the login page to already 
    logged-in users.
---------------------------------------------------*/


$user = new User();

if($user->loggedIn()){
    redirect('protected.php');
}



/*--------------------------------------------------
    Handle submitting the login form via AJAX
---------------------------------------------------*/


try{

    if(!empty($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

        // Output a JSON header

        header('Content-type: application/json');

        // Is the email address valid?

        if(!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            throw new Exception('Please enter a valid email.');
        }

        // This will throw an exception if the person is above 
        // the allowed login attempt limits (see functions.php for more):
        rate_limit($_SERVER['REMOTE_ADDR']);

        // Record this login attempt
        rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);

        // Send the message to the user

        $message = '';
        $email = $_POST['email'];
        $subject = 'Your Login Link';

        if(!User::exists($email)){
            $subject = "Thank You For Registering!";
            $message = "Thank you for registering at our site!\n\n";
        }

        // Attempt to login or register the person
        $user = User::loginOrRegister($_POST['email']);


        $message.= "You can login from this URL:\n";
        $message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

        $message.= "The link is going expire automatically after 10 minutes.";

        $result = send_email($fromEmail, $_POST['email'], $subject, $message);

        if(!$result){
            throw new Exception("There was an error sending your email. Please try again.");
        }

        die(json_encode(array(
            'message' => 'Thank you! We\'ve sent a link to your inbox. Check your spam folder as well.'
        )));
    }
}
catch(Exception $e){

    die(json_encode(array(
        'error'=>1,
        'message' => $e->getMessage()
    )));
}

/*--------------------------------------------------
    Output the login form
---------------------------------------------------*/

?>

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8"/>
        <title></title>

        <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">

        <!-- The main CSS file -->
        <link href="assets/css/style.css" rel="stylesheet" />

        <!--[if lt IE 9]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <form id="login-register" method="post" action="index.php">

            <h1>Login or Register</h1>

            <input type="text" placeholder="your@email.com" name="email" autofocus />
            <p>Enter your email address above and we will send <br />you a login link.</p>

            <button type="submit">Login / Register</button>

            <span></span>

        </form>

        <footer>
            <a class="tz" href="#">#</a>
            <div id="tzine-actions"></div>
            <span class="close"></span>
        </footer>

        <!-- JavaScript Includes -->
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>
$(function(){

    var form = $('#login-register');

    form.on('submit', function(e){

        if(form.is('.loading, .loggedIn')){
            return false;
        }

        var email = form.find('input').val(),
            messageHolder = form.find('span');

        e.preventDefault();

        $.post(this.action, {email: email}, function(m){

            if(m.error){
                form.addClass('error');
                messageHolder.text(m.message);
            }
            else{
                form.removeClass('error').addClass('loggedIn');
                messageHolder.text(m.message);
            }
        });

    });

    $(document).ajaxStart(function(){
        form.addClass('loading');
    });

    $(document).ajaxComplete(function(){
        form.removeClass('loading');
    });
});
bro(madalinivascu)我现在将您的第一个代码javascript放在script.js中,它运行良好,因为它向http头电子邮件发送两个值:xxxxx@xxx.xx和验证码:XXXXXXXXXXXXX

script.js中的新代码变成:

$(function(){

    var form = $('#login-register');

    form.on('submit', function(e){

        if(form.is('.loading, .loggedIn')){
            return false;
        }

        var email = form.find('input').val(),
            messageHolder = form.find('span');

        e.preventDefault();

                //This code i added
                $.post(this.action, {email: email, captcha: grecaptcha.getResponse()}, function(m){

            if(m.error){
                form.addClass('error');
                messageHolder.text(m.message);
            }
            else{
                form.removeClass('error').addClass('loggedIn');
                messageHolder.text(m.message);
            }
        });

    });

    $(document).ajaxStart(function(){
        form.addClass('loading');
    });

    $(document).ajaxComplete(function(){
        form.removeClass('loading');
    });
});
但是在index.php文件中,我不知道我把代码放在了哪里:

$secret="YOUR_SECRET";
$response=$_POST["captcha"];

$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if (!$captcha_success->success) {
  //This user was not verified by recaptcha, send error message

}
else {
  //This user is verified by recaptcha, continue

}
我试了几次,都没有成功。 php代码:(不工作)


通过ajax将验证码响应发送到php脚本:

$.post(this.action, {email: email,captcha: grecaptcha.getResponse()}, function(m){
在php中,您需要这样做

$secret="YOUR_SECRET";
$response=$_POST["captcha"];

$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if (!$captcha_success->success) {
  //This user was not verified by recaptcha, send error message

}
else {
  //This user is verified by recaptcha, continue

}

经过几次尝试,我找到了将capcha添加到表单中的正确方法。 正确的代码是: script.js(ajax):

index.php:

<?php

require_once 'includes/main.php';


/*--------------------------------------------------
    Handle visits with a login token. If it is
    valid, log the person in.
---------------------------------------------------*/


if(isset($_GET['tkn'])){

    // Is this a valid login token?
    $user = User::findByToken($_GET['tkn']);

    if($user){

        // Yes! Login the user and redirect to the protected page.

        $user->login();
        redirect('protected.php');
    }

    // Invalid token. Redirect back to the login form.
    redirect('index.php');
}



/*--------------------------------------------------
    Handle logging out of the system. The logout
    link in protected.php leads here.
---------------------------------------------------*/


if(isset($_GET['logout'])){

    $user = new User();

    if($user->loggedIn()){
        $user->logout();
    }

    redirect('index.php');
}


/*--------------------------------------------------
    Don't show the login page to already 
    logged-in users.
---------------------------------------------------*/


$user = new User();

if($user->loggedIn()){
    redirect('protected.php');
}


/*--------------------------------------------------
            get result of captcha
---------------------------------------------------*/
if($_SERVER["REQUEST_METHOD"] === "POST")
    {
        //form submitted

        //check if other form details are correct

        //verify captcha
        $recaptcha_secret = "-----your-secret-key-----";
        $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['captcha']);
        $response = json_decode($response, true);

    }

/*--------------------------------------------------
    Handle submitting the login form via AJAX
---------------------------------------------------*/

try{


    if(!empty($_POST)  && isset($_POST["captcha"]) && isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

        // Output a JSON header

        header('Content-type: application/json');

        // Is the email address valid?

        if(!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            throw new Exception('Please enter a valid email.');
        }

       if(!$response["success"] === true){
            throw new Exception('Please check captcha.');
        }

        // This will throw an exception if the person is above 
        // the allowed login attempt limits (see functions.php for more):
        rate_limit($_SERVER['REMOTE_ADDR']);

        // Record this login attempt
        rate_limit_tick($_SERVER['REMOTE_ADDR'], $_POST['email']);

        // Send the message to the user

        $message = '';
        $email = $_POST['email'];
        $subject = 'Your Login Link';

        if(!User::exists($email)){
            $subject = "Thank You For Registering!";
            $message = "Thank you for registering at our site!\n\n";
        }

        // Attempt to login or register the person
        $user = User::loginOrRegister($_POST['email']);


        $message.= "You can login from this URL:\n";
        $message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

        $message.= "The link is going expire automatically after 10 minutes.";

        $result = send_email($fromEmail, $_POST['email'], $subject, $message);

        if(!$result){
            throw new Exception("There was an error sending your email. Please try again.");
        }

        die(json_encode(array(
            'message' => 'Thank you! We\'ve sent a link to your inbox. Check your spam folder as well.'
        )));
    }


}
catch(Exception $e){

    die(json_encode(array(
        'error'=>1,
        'message' => $e->getMessage()
    )));
}

/*--------------------------------------------------
    Output the login form
---------------------------------------------------*/

?>

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8"/>
        <title>#</title>

        <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">

        <!-- The main CSS file -->
        <link href="assets/css/style.css" rel="stylesheet" />

        <!--[if lt IE 9]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
                        <script src="https://www.google.com/recaptcha/api.js"></script>
    </head>

    <body>

        <form id="login-register" method="post" action="index.php">

            <h1>Login or Register</h1>

            <input type="text" placeholder="your@email.com" name="email" autofocus />
            <p>Enter your email address above and we will send <br />you a login link.</p>

                        <div class="g-recaptcha" data-sitekey="------yoursitekey------"></div>

            <button type="submit" name="submit">Login / Register</button>

            <span></span>

        </form>

        <footer>
            <a class="tz" href="#"></a>
            <div id="tzine-actions"></div>
            <span class="close"></span>
        </footer>

        <!-- JavaScript Includes -->
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>

我发现了很多问题,在哪里,有多少,他们怎么说?我不知道在哪里添加验证码Google在AJAX js或php文件中,或者在这两个文件中。在前端和后端,在前端附加html和js,在后端,您检查通过ajaxi接收到的响应。尝试将此代码添加到文件php但不工作。我尝试将此代码添加到文件php但不工作$response=$\u POST[“g-recaptcha-response”];$url='';$data=array('secret'=>'--秘钥--','response'=>$\u POST[“g-recaptcha-response”])。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。我在你的代码中没有看到验证码的痕迹,验证码在哪里?我把代码放在php中。但我不知道如何把一个完整的Java代码。什么Java?php和javascript与java有什么关系?我是说java脚本,我的兄弟。请看答案,我把完整的代码放在底部的答案中。我看不到任何答案