简体   繁体   English

使用jquery和php登录Ajax

[英]Ajax login using jquery and php

I need some help with the login system. 我需要有关登录系统的帮助。

Im following this tutorial: http://tutsforweb.blogspot.pt/2012/05/ajax-login-form-with-jquery-and-php.html 我正在遵循此教程: http : //tutsforweb.blogspot.pt/2012/05/ajax-login-form-with-jquery-and-php.html

Everything works fine and its exactly what I want for my login system, but instead of only make login if the username and password are correct and displaying the message "Wrong username or password" if: 一切正常,并且完全符合我对登录系统的要求,但如果用户名和密码正确,则只能进行登录,并在以下情况下显示消息“用户名或密码错误”:

  • the fields are empty 字段为空
  • username doesnt exist 用户名不存在
  • password is wrong 密码错误

I wold like to make it to display a diferent message for each one of cases 我很想让每种情况都显示不同的消息

Can someone tell me how to do that? 有人可以告诉我该怎么做吗? Pls, I understand 0 of ajax and jquery. 请理解,我了解0的ajax和jquery。

This is the code of index.php 这是index.php的代码

<script type="text/javascript">
$(document).ready(function(){
    $("#login_a").click(function(){
        $("#shadow").fadeIn("normal");
         $("#login_form").fadeIn("normal");
         $("#user_name").focus();
    });
    $("#cancel_hide").click(function(){
        $("#login_form").fadeOut("normal");
        $("#shadow").fadeOut();
   });
   $("#login").click(function(){

        username=$("#user_name").val();
        password=$("#password").val();
         $.ajax({
            type: "POST",
            url: "login.php",
            data: "name="+username+"&pwd="+password,
            success: function(html){
              if(html=='true')
              {
                $("#login_form").fadeOut("normal");
                        $("#shadow").fadeOut();
                        $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");

              }
              else
              {
                    $("#add_err").html("Wrong username or password");
              }
            },
            beforeSend:function()
            {
                 $("#add_err").html("Loading...")
            }
        });
         return false;
    });
});
</script>
</head>
<body>
    <div id="profile">
    <a id="login_a" href="#">login</a>
    </div>
    <div id="login_form">
        <div class="err" id="add_err"></div>
        <form action="login.php">
            <label>User Name:</label>
            <input type="text" id="user_name" name="user_name" />
            <label>Password:</label>
            <input type="password" id="password" name="password" />
            <label></label><br/>
            <input type="submit" id="login" value="Login" />
            <input type="button" id="cancel_hide" value="Cancel" />
        </form>
    </div>
    <div id="shadow" class="popup"></div>
</body>

And this is the code of login.php 这是login.php的代码

<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
$mysqli=mysqli_connect('localhost','root','','logintest');

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
        $row=mysqli_fetch_array($result);
        if( $num_row >=1 ) {
            echo 'true';
            $_SESSION['user_name']=$row['username'];
        }
        else{
            echo 'false';
        }
?>

PS: I had other topic with some wierd code edited by me, but I think this is more expecific of what Is my problem and what I want. PS:我还有其他话题,我编辑过一些奇怪的代码,但是我认为这更确切地说明了我的问题是什么,我想要什么。

If someone could help me I appreciate that. 如果有人可以帮助我,我将不胜感激。

It is better to not change the error message. 最好不要更改错误消息。 For security reasons almost all login script will give as little information as possible. 出于安全原因,几乎所有登录脚本都将提供尽可能少的信息。 The reason is that hackers will get the information as well and for example, they know that the username that was filled out is correct and can try to brute force the password. 原因是黑客也将获得该信息,例如,他们知道填写的用户名是正确的,并且可以尝试强行使用密码。

There are a number of plugins and tools you can use to validate that the form elements (username and password) have values before making the AJAX request. 在发出AJAX请求之前,可以使用许多插件和工具来验证表单元素(用户名和密码)是否具有值。 But at its simplest you can just check the input values yourself. 但是最简单的是,您可以自己检查输入值。 Notice where you get those values: 请注意您从哪里获得这些值:

username=$("#user_name").val();
password=$("#password").val();

Those two variables are now string variables. 这两个变量现在是字符串变量。 You can examine their contents and respond accordingly. 您可以检查其内容并做出相应的响应。 So perhaps before making the AJAX request you do something as simple as: 因此,也许在发出AJAX请求之前,您要做的事情很简单:

if (username === '' || password === '') {
  $("#add_err").html("Please enter both a username and a password");
  return false;
}

That way if either of those values is an empty string it will display an error and exit the function. 这样,如果这些值中的任何一个为空字符串,它将显示错误并退出函数。 If both of them are not empty strings, it continues with your current code. 如果它们都不是空字符串,则继续您当前的代码。

A couple of other important notes (which I made in comments above, but are important enough to include in an answer)... 其他一些重要的注释(我在上面的评论中做了一些注释,但是足够重要,可以包含在答案中)...

1) Never store passwords in plain text. 1) 切勿以纯文本形式存储密码。 Seriously, never. 说真的,永远不会。 There's no reason to ever do this. 没有理由这样做。 Passwords should be obscured by a 1-way irreversible hash. 密码应以1向不可逆的哈希值遮盖。 Store that hash. 存储该哈希。 When a user enters their password, hash what they enter and compare the hashes. 用户输入密码时,请对输入的内容进行哈希处理并比较哈希值。 You should never be able to read somebody's password. 您应该永远无法读取别人的密码。

2) Don't create different error messages depending on how the login fails. 2)根据登录失败怎么不创建不同的错误消息。 Just say that the login failed and that's all. 只需说登录失败,仅此而已。 Telling them which piece was wrong (the username or the password) provides an opportunity for an attacker to gather information about users. 告诉他们哪一部分错了(用户名或密码)为攻击者提供了收集有关用户信息的机会。 Even a small opportunity, but it makes the attacker's job easier. 即使是很小的机会,但这也使攻击者的工作更加轻松。 Don't give out such information. 不要透露这些信息。

Within the scope of functionality you are trying to achieve, I think you would want to handle all the 3 additional conditions from PHP only (though first condition of fields being empty can be checked using jQuery) but to keep it clean, you can test all the conditions using PHP and return different cases from php that will be accordingly handled by jQuery. 内的功能,你正在努力实现的范围,我想你会想处理来自PHP所有3个附加条件只,但保持干净(虽然场是空的第一个条件可以使用jQuery进行检查),你可以测试所有使用PHP的条件,并从php返回不同情况,jQuery将相应地处理这些情况。

To give you understanding of how ajax and jquery are working here, looking at these lines of code: 为了让您了解ajax和jquery在这里是如何工作的,请查看以下代码行:

$.ajax({
        type: "POST",
        url: "login.php",
        data: "name="+username+"&pwd="+password,
        success: function(html){

The ajax methods call the login.php file by POSTing data on it. ajax方法通过在其中登录数据来调用login.php文件。 Whatever is returned or echoed by PHP will be fetched in the success function through the parameter 'html'. PHP返回或回显的所有内容都将通过参数'html'在成功函数中获取。 Note that 'html' is just a variable name being used here though actually just a string will be fetched here. 请注意,“ html”只是在此处使用的变量名,尽管实际上仅会在此处获取字符串。

Eg In the php, if login is successful 'true' is echoed and the same text is fetched in html variable in the success function. 例如,在php中,如果登录成功,则返回“ true”,并在成功函数的html变量中提取相同的文本。 The condition if(html=='true') just checks that and hides the form. 条件if(html =='true')只是检查并隐藏表单。

One way to achieve your objective is you define different return values for each case from PHP which can be: 1: Login successful 2: One of the fields (username or password) are empty 3: Username doesn't exist 4: Password is wrong 达到你的目的的一种方法是,你从PHP每种情况下可以定义不同的返回值:1:登录成功2:其中一个字段(用户名或密码)为空3:用户名不存在4:密码是错的

For which the PHP code will be like this: 为此,PHP代码将如下所示:

    <?php
        session_start();
        $username = $_POST['name'];
        $password = $_POST['pwd'];
        // Check if any of the fields is empty
        if(empty($username) || empty($password)){
            echo '2';
        } else {
            $mysqli=mysqli_connect('localhost','root','','logintest');

            // Check if username exists
            $query = "SELECT * FROM users WHERE username='$username'";
            $result = mysqli_query($mysqli,$query)or die(mysqli_error());
            $num_row = mysqli_num_rows($result);
            if($num_row == 0){
                echo '3';
            } else {
                $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
                $result = mysqli_query($mysqli,$query)or die(mysqli_error());
                $num_row = mysqli_num_rows($result);
                $row=mysqli_fetch_array($result);
                if( $num_row >=1 ) {
                    echo '1';
                    $_SESSION['user_name']=$row['username'];
                }
                else{
                    echo '4';
                }
            }
        }
?>

Now, these returns values can be handled in jQuery with switch statement 现在,可以使用switch语句在jQuery中处理这些返回值

success: function(html){
              switch(html)
              {

                case '1': // Login successful 
                        $("#login_form").fadeOut("normal");
                        $("#shadow").fadeOut();
                        $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
                        break;

                case '2': // Empty Field
                    $("#add_err").html("Please fill both username and password");
                        break;
                case '3': // username doesn't exist
                        $("#add_err").html("Username doesn't exist");
                        break;
                case '4': //Password is wrong
                        $("#add_err").html("Password is wrong");
                        break;
            }
        }

I hope this will help you getting what you want 我希望这会帮助您得到想要的东西

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

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