PHP注意:未定义的索引:密码

注册帐户效果很好。我可以使用电子邮件,加密的密码等将用户添加到我的数据库中,但是我无法以现有用户身份登录。

POST'logIn'的检查似乎根本没有运行。除了在ajax响应中检查“失败”时,我没有控制台响应,“成功”或“错误”。

Here's the console output from my ajax statement checking for 'failed': <br /><b>Notice</b>: Undefined index: password in<b>/opt/lampp/htdocs/index.php</b> on line <b>42</b><br /> failed

此代码来自youtube教程,该教程似乎对评论中的其他所有人都有效。因此,我下载并运行了原始源代码,它具有相同的问题。我认为问题出在我的PHP配置或SQL数据库中,但我不确定。我是PHP和SQL的新手。

我试图进行一些研究以找出问题所在,并且一个站点建议密码可能已被截断,因为它需要60个字符,但我不认为这是问题所在:密码设置为utf8_unicode_ci,VARCHAR(255)

我在Crostini / chromebook上运行XAMPP并使用phpmyadmin

以下是有关我的设置的一些详细信息: 服务器:通过UNIX套接字的Localhost 服务器类型:MariaDB 服务器连接:未使用SSL文档 服务器版本:10.4.11-MariaDB-源分发 协议版本:10 用户:root @ localhost 服务器字符集:cp1252西欧(latin1)

Apache / 2.4.43(Unix)OpenSSL / 1.1.1g PHP / 7.4.5 mod_perl / 2.0.8-dev Perl / v5.16.3 数据库客户端版本:libmysql-mysqlnd 7.4.5 PHP扩展:mysqli文档curl文档mbstring文档 PHP版本:7.4.5

PHPmyadmin 5.0.2版(最新)

这是我的代码:

<?php
    session_start();
    $loggedIn = false;

    if (isset($_SESSION['loggedIn']) && isset($_SESSION['name'])) {
        $loggedIn = true;
    }

    $conn = new mysqli('localhost', 'root', '', 'commentSystem');

    if (isset($_POST['register'])){
        $name = $conn->real_escape_string($_POST['name']);
        $email = $conn->real_escape_string($_POST['email']);
        $password = $conn->real_escape_string($_POST['password']);

        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $sql = $conn->query("SELECT id FROM users WHERE email='$email'");
            if ($sql->num_rows > 0) {
                exit('userExists');
            } else {
                $ePassword = password_hash($password, PASSWORD_BCRYPT);
                $conn->query("INSERT INTO users (name,email,password,createdOn) VALUES ('$name','$email','$ePassword',NOW())");

                $sql = $conn->query("SELECT id FROM users ORDER BY id DESC LIMIT 1");
                $data = $sql->fetch_assoc();

                $_SESSION['loggedIn'] = 1;
                $_SESSION['name'] = $name;
                $_SESSION['email'] = $email;
                $_SESSION['userID'] = $data['id'];

                //if ($conn->error){printf("Errormessage: %s\n", $conn->error);}

                exit(' success');
            }       
        } else
        exit('failed');
    }

    if (isset($_POST['logIn'])){
    $email = $conn->real_escape_string($_POST['email']);
    $password = $conn->real_escape_string($_POST['password']);

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $sql = $conn->query("SELECT id, password, name FROM users WHERE email='$email'");
        if ($sql->num_rows == 0) {
            exit('failed');
            } else {
          $data = $sql->fetch_assoc();
          $passwordHash = $data['password'];

          if (password_verify($password, $passwordHash)) {
            $_SESSION['loggedIn'] = 1;
            $_SESSION['name'] = $data['name'];
            $_SESSION['email'] = $email;
            $_SESSION['userID'] = $data['id'];

            exit('success');
          } else {
                exit('failed');
            }
        }
    } else
      exit('failed');
  }
?>

<!DOCTYPE html>
<html>
<head>
    <meta carset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="x-UA-Compatible" content="ie=edge">
    <title>PHP Comment System</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <style type="text/css">
        .user {font-weight:bold;color:black}
        .time {color:gray}
        .replies .comment {margin-top:20px}
        .replies {margin-left:20px}
    </style>
</head>
<body>
    <div class="modal" id="registerModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Registration</h5>
                </div>
                <div class="modal-body">
                    <input type="text" class="form-control" id="userName" placeholder="Enter Your Name"><br>
                    <input type="text" class="form-control" id="userEmail" placeholder="Enter Your Email"><br>
                    <input type="text" class="form-control" id="userPassword" placeholder="Enter Your Password">
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" data-dismiss="modal" id="registerBtn">Register</button>
                    <button class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="loginModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">LogIn</h5>
                </div>
                <div class="modal-body">
                    <input type="text" class="form-control" id="userLEmail" placeholder="Enter Your Email"><br>
                    <input type="text" class="form-control" id="userLPassword" placeholder="Enter Your Password">
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" data-dismiss="modal" id="loginBtn">Log In</button>
                    <button class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <div class="container" style="margin-top:50px;">
        <div class="row">
            <div class="col-md-12" align="right">
                <?php
                    if (!$loggedIn) {
                        echo '
                            <button class="btn btn-primary" data-toggle="modal" data-target="#registerModal">Register</button>
                            <button class="btn btn-success" data-toggle="modal" data-target="#loginModal">Log In</button>
                        ';
                    }   else {
                        echo '
                            <sub style="float:left">Welcome 
                        ' . $_SESSION['name'] . '!</sub>
                        <a href="logout.php" class="btn btn-warning">Log Out</a>
                        ';
                    }
                ?>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <h1>Page Header</h1>
                <p>--Page Content--</p>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <textarea class="form-control" placeholder="Add Public Comment" cols="30" rows="10"></textarea>
                <button class="btn btn-primary">Add Comment</button>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="userComments">
                    <div class="comment">
                        <div class="user"><span class="time"></span></div>
                        <div class="userComment"></div>
                        <div class="replies"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
<script>
    $(document).ready(function () {
        $("#registerBtn").on('click', function() {
            var name = $("#userName").val();
            var email = $("#userEmail").val();
            var password = $("#userPassword").val();

            if (name != "" && email != "" && password != ""){
                $.ajax({
                    url: 'index.php',
                    method: 'POST',
                    dataType: 'text',
                    data: {
                        register: 1,
                        name: name,
                        email: email,
                        password: password
                    }, success: function (response){
                        if (response === 'failedEmail') {
                            alert ("Please insert a valid email address!");
                        }   else if (response === 'failedUserExists') {
                                alert ("This email is already registered");
                        } else {
                            window.location = window.location;
                        }
                    }
                });
            }
        });

        $("#loginBtn").on('click', function(){ 
            var email = $("#userLEmail").val();
            var password = $("userLPassword").val();

            if (email != "" && password != "") {
                $.ajax({
                    url: 'index.php',
                    method: 'POST',
                    dataType: 'text',
                    data: {
                        logIn: 1,
                        email: email,
                        password: password
                    }, 
                    success: function (response) { 
                        if (response == 'failed'){
                            alert("Invalid username or password");
                        } else {
                            console.log(response);
                            //window.location = window.location;
                        }
                    }
                });
            } else {
                alert("Required input is empty!")
            }
        });
    });
</script>
</html>
评论
  • JJ初始化
    JJ初始化 回复

    问题在这里:

     $("#loginBtn").on('click', function(){ 
            var email = $("#userLEmail").val();
            var password = $("userLPassword").val(); //this line
    

    you forgot to add # before userLPassword