如何显示php登录错误?

时间:2016-11-02 18:52:58

标签: php

我正在开发一个简单的登录系统来提高我的知识,我想知道如果用户输入错误的密码或用户名或者他没有填写任何字段我可以显示警告消息,我已经开始但是我不确定它是否是正确的方式,我不知道如何使用登录表单在页面中显示消息。非常感谢你的帮助:))

这是我的登录控制器

<?php
/**
 * Nome File : ctrl_login.php
 * Descrizione: File che gestisce i dati inseriti nella pagina di login
 */

include('../config/konasi.php');
include('functions.php');

$user_name   = check_input($_POST['username']);
$user_password = check_input($_POST['userpassword']);

if (!$user_name || !$user_password) {
    echo "Non hai inserito username o password";
    exit();
}

if ($stmt = mysqli_prepare($conn, "SELECT user_password FROM users WHERE user_name= ? ")) {
    /* Bind parameters: s - string, b - blob, i - int, etc */
    $stmt -> bind_param("s", $user_name);
    /* Execute it */
    $stmt -> execute();
    /* Bind results */
    $stmt -> bind_result($result);
    /* Fetch the value */
    $stmt -> fetch();
    /* Close statement */
    $stmt -> close();
}

if(password_verify($user_password, $result)) {    
    echo "you are connected!";    
} else {        
    echo "Ops, wrong password";
}

mysqli_close($conn);

这是我的索引文件,其中包含登录表单

<form class="form-signin" action="includes/ctrl_login.php" method="post">
    <h3 class="form-signin-heading">Login </h3>

    <div class="form-group">
        <label for="username" class="sr-only">Username </label>
        <input type="text" id="username" name="username" class="form-control" placeholder="Username">
    </div>
    <div class="form-group">
        <label for="password" class="sr-only">Password</label>
        <input type="password" id="password" name="userpassword" class="form-control" placeholder="Password">
    </div>

    <button class="btn btn-lg btn-primary btn-block" type="submit">login</button>
</form>

这是我的function.php

function check_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

2 个答案:

答案 0 :(得分:0)

其中一种方法是在控制器中设置会话变量并将其重定向到登录页面,然后在登录页面中显示它们。

将下面的行放在您的登录页面和控制器上方。

session_start();

在登录表单页面中添加以下行

<p><?=$_SESSION['error_msg']?></p>

在您的控制器而不是echo消息中将它们设置在会话变量中。比如

$_SESSION['error_msg'] = 'Ops, wrong password';
header("location: link_to_login_form");
exit();

我希望这会有所帮助。

答案 1 :(得分:-1)

只需使用此功能检查登录:

function login_check($username,$pwd){

    if ($stmt = mysqli_prepare($conn, "SELECT COUNT(id) FROM `users` WHERE `user_name`=? AND `user_password`=? ")) {
        /* Bind parameters: s - string, b - blob, i - int, etc */
        $stmt -> bind_param("ss", $user_name,,$pwd);
        /* Execute it */
        $stmt -> execute();
        /* Bind results */
        $stmt -> bind_result($result);
        /* Fetch the value */
        $login_row=$stmt -> fetch();

        if($login_row[0]>=1) {
            echo "You are connected";
        } else {
            echo "Ops, wrong password";
        }

        /* Close statement */
        $stmt -> close();
    }   
}