Форма входа в PHP и JS говорит, что пользователь не существует, ошибка - PullRequest
0 голосов
/ 07 декабря 2018

Мне удалось создать успешную форму регистрации, которая передает информацию в базу данных с помощью запросов PDO, и она успешно создает сеанс после регистрации пользователя и т. Д.

Когда дело доходит до входа в систему наФорма входа, я получаю сообщение об ошибке «Пользователь не существует», хотя он существует в базе данных.Кажется, я не могу понять, почему возникает эта ошибка, поскольку я использовал подобный код для регистрации.

Ниже приведен код HTML / PHP для внешнего интерфейса сайта.

<?php
    //allow the config
    define('__CONFIG__', true);
    //require the config
    require_once "inc/config.php";  //possibly have to change the location
 ?>

<!DOCTYPE html>
<html>
<head>
    <!-- UIKit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.24/css/uikit.min.css" />

    <title>Login Page</title>
    <base href="/"/>

</head>
<body>

<div class="uk-section uk-container">
    <div class="uk-grid uk-child-width-1-3@s uk-child-width-1-1" uk-grid></div>

                    <h2><b><center>Login</center></b></h2>

                <form style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;" class="uk-form-stacked js-login">

                    <div class="uk-margin">
                        <label class="uk-form-label" for="form-stacked-text"><b>Email:</b></label>
                        <div class="uk-form-controls">
                            <input class="uk-input" id="form-stacked-text" type="email" required='required' placeholder="Insert Email">
                        </div>
                    </div>
                    <div class="uk-margin">
                        <label class="uk-form-label" for="form-stacked-text"><b>Password:</b></label>
                        <div class="uk-form-controls">
                            <input class="uk-input" id="form-stacked-text" type="Password" required='required' placeholder="Insert Password">
                        </div>
                    </div>

                    <div class="uk-margin uk-alert uk-alert-danger js-error" style='display: none;'></div>

                    <div class="uk-margin">
                        <label><center>Don't have an account? <a href='comp1687/register.php'>Create one now!</a></center></label>
                        <center><button class="uk-button uk-button-default" type="submit"><b>LOGIN</b></button></center>
                    </div>

                </form>
</div>

<?php require_once "inc/footer.php"; ?>


</body>
</html>

Ниже приведен AJAX-код login.php, используемый для проверок.

<?php 

    // Allow the config
    define('__CONFIG__', true);

    // Require the config
    require_once "../inc/config.php";  //possibly have to change the location

    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        // Always return JSON format
        // header('Content-Type: application/json');

        $return = [];

        $email = Filter::String( $_POST['email'] );
        $password = $_POST['password'];

        $user_found = User::Find($email, true);

        if($user_found) {
            // User exists, try and sign them in
            $user_id = (int) $user_found['user_id'];
            $hash = (string) $user_found['password'];

            if(password_verify($password, $hash)) {
                // User is signed in
                $return['redirect'] = 'dashboard.php?message=welcome'; //possibly have to change the location

                $_SESSION['user_id'] = (int) $user_id;
            } else {
                // Invalid user email/password combo
                $return['error'] = "Invalid user email/password combo";
            }

        } else {
            // They need to create a new account
            $return['error'] = "You do not have an account. <a href='register.php'>Create one now?</a>";
}

        echo json_encode($return, JSON_PRETTY_PRINT);
    } else {
        ///Kill the script. Redirect the user.
        exit('Invalid URL');
    }
?>

И, наконец, код main.js выглядит следующим образом

.on("submit", "form.js-login", function(event) {
    event.preventDefault();

    var _form = $(this);
    var _error = $(".js-error", _form);

        var dataObj = {
            email: $("input[type='email']", _form).val(),
            password: $("input[type='password']", _form).val(),

        };



    if(dataObj.email.length < 6) {
        _error
            .text("Please enter a valid email address")
            .show();
        return false;
    } else if (dataObj.password.length < 8) {
        _error
            .text("Please enter a password that is at least 8 characters long.")
            .show();
        return false;
    }

    // Assuming the code gets this far, we can start the ajax process
    _error.hide();

    $.ajax({
        type: 'POST',
        url: 'ajax/login.php', 
        data: dataObj,
        dataType: 'json',
        async: true,
    })
        .done(function ajaxDone(data) {
            // Whatever data is
            if(data.redirect !== undefined) {
                window.location = data.redirect;
                console.log('data');
            } else if(data.error !== undefined) {
                _error
                    .html(data.error)
                    .show();
                console.log('data');
            }
        })
        .fail(function ajaxFailed(e) {
            //this failed
            console.log(e);

        })
        .always(function ajaxAlwaysDoThis(data) {
            //always do
            console.log('Always');
        })

    return false;
})

Пользователь находит класс сфункция поиска

public static function Find($email, $username,  $return_assoc = false) {

        $con = DB::getConnection();

        // Make sure the user does not exist. 
        $email = (string) Filter::String( $email );

        $findUser = $con->prepare("SELECT user_id, password FROM users WHERE email = (:email) AND username = (:username)  LIMIT 1");
        $findUser->bindParam(':email', $email, PDO::PARAM_STR);
        $findUser->bindParam(':username', $username, PDO::PARAM_STR);

        $findUser->execute();


        if($return_assoc) {
            return $findUser->fetch(PDO::FETCH_ASSOC);
        }

        $user_found = (boolean) $findUser->rowCount();
        return $user_found;
    }

Ответы [ 2 ]

0 голосов
/ 07 декабря 2018

Вы передаете 'true' в качестве второй переменной методу User::Find, который затем интерпретируете как строковый литерал в запросе MySQL.('true')

Используете ли вы электронную почту в качестве имени пользователя или отдельное поле имени пользователя?Я не могу найти это в вашем HTML.Если вы просто используете электронную почту, вы можете избавиться от второго параметра в методе Find и удалить оба:

 AND username = (:username)

 $findUser->bindParam(':username', $username, PDO::PARAM_STR);
0 голосов
/ 07 декабря 2018
//Are you receiving some correct ouput from your php code? 
//To check it, after this code,
else {
            // They need to create a new account
            $return['error'] = "You do not have an account. <a href='register.php'>Create one now?</a>";
}

// Добавьте эти две строки:

var_dump($user_found);
var_dump($return);
die();

// И пришлите мне вывод.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...