PHP登录代码不起作用,用户仍然卡在登录页面上

时间:2016-05-06 01:03:05

标签: php mysql

我是PHP的新手,无法找到以下代码无法解决的原因。这应该很容易,但我无法弄清楚这一点。此代码不会产生错误,并且phpAdmin SQL控制台中的SQL语句是正确的。我搜索过web& StackOverflow,但无法找到一个好的答案。怎么了? 所有用户(无论是否在数据库中)都会被忽略并停留在登录页面上。

<?php
session_start();

//create function to check login form for admin or other type of user.      
//Redirect the admin user to the welcome page.

function login()
    {
        //strip login and password using in-build htmlspecialchars function
        $value1 = htmlspecialchars($_POST['login']);
        $value2 = htmlspecialchars($_POST['password']);    

        //set variables for the db connection
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "mydb";
        $loggedin = '';

        //Create new connection to db            
        $conn = new mysqli($servername, $username, $password, $dbname);

        //Check connection and handle any error
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
            header('Locatin: login.php');
        }
        else {               
            //check if super admin user exists in db      
            $sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
            $result = mysqli_query($conn,$sql);

            //check to see if query returns any rows
            if(mysql_num_rows(($result) > 0) {
                include 'welcome.php';
            }

            //check if the password and username match
            if(($username === $value1) && ($password === $value2)) {
                $_SESSION['loggedin'] = TRUE;
                echo "Hello ".$value1.", you are logged in!<br>";
            }
            //send user error message if login/username and password wrong
            else {
                echo "Incorrect username or password<br>";
                include 'login.php';
            }

            //close the db connection               
            $conn->close();
        }
?>

登录表单

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>

//function to check the form
function chkForm()
    {
        //determine the number of elements in the user login form
        var intFormLen = document.forms[0].elements.length;

        //loop through the form fields to see that a value has been input
        for (var i = 0; i < intFormLen; i++) {
            if (document.forms[0].elements[i].value == "") {
                //send user an error message if login field empty
                document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
                document.forms[0].elements[i].focus();                                
                return false;
            }
        }

        //clear the form fields
        function clearWarn(fieldName)
            {
                document.getElementById(fieldName).innerHTML = "";                  
                return true;
            }

        return;
    }   
</script>
</head>
<body>
<h2>Admin Login</h2>           
<div class="phpEcho">
    <div class="formLayout">
        <form action="#" method="post" onsubmit="return chkForm();">
            <label for="login">Login:</label>
            <input type="text"name="login" onchange="return clearWarn('fieldName')">
            <div id="login" style="color:red"></div><br>
            <label for="password">Password:</label>
            <input type="password" name="password" onchange="return clearWarn('fieldName')">
            <div id="password" style="color:red"></div><br><br>
            <input type="submit" name="cmdSubmit" value="Log in">
        </form>
    </div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您设置了form action="#",但未在JavaScript中提交。

正如Jason所指出的那样,chkForm()将永远不会返回true,这也会阻止表单提交。

答案 1 :(得分:0)

此脚本存在许多应该解决的问题。我将介绍一些可能对您有帮助的事情:

1)我建议使用某种config / bootstrap文件包含在包含可重用元素和启动会话的文档中。要求/只包括一次。

<强> /config.php

define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();

2)您需要分离您的功能,重要的是您的数据库连接,无论是按类还是按功能。您希望将任务分开,以便于重复使用。

这是一个例子(我将使用PDO,因为我对它更熟悉,但原理是相同的):

<强> /functions/connection.php

function connection()
    {
        // This is just a really basic connection, one could expand on this
        return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
    }

<强> /functions/login.php

/*
** @param $username [string] by making this a param, you can manually log in users outside of POST
** @param $password [string] same as username
** @param $conn [resource] You will want to inject your connection into this
**                         in order to use it. Don't make the connection 
**                         inside. May as well reuse resources already active
** @return [bool] If you return TRUE or FALSE, that will tell your script
**                whether the login succeeded or failed for notification
*/

function login($username,$password,$conn)
    {
        // Don't worry about stripping down the username/pass, just bind
        // the username and match the password
        // You need to select from your user table (or whatever table
        // you are storing your usernames for your site)
        $query = $conn->prepare("select * from `users` where `username` = :0");
        $query->execute(array(':0'=>$username));
        $result = $query->fetch(PDO::FETCH_ASSOC);
        if(empty($result))
            return false;
        // You will want to use password_hash to save passwords
        if(!password_verify($password,$result['password']))
            return false;
        // I use htmlspecialchars here so I don't forget when echoing to page
        // but you can do it at the time you echo to browser
        $_SESSION['first_name'] = htmlspecialchars($result['first_name']);
        //etc....
        return true;
    }

使用:

<强>的index.php

// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');

// Set connection
$con    = connection();

// See if a post has been made
if(isset($_POST['login'])) {
    $loggedin = login($_POST['login'],$_POST['password'],$con);
}

// If the login attempt made
if(isset($loggedin)) {
    // If successful
    if($loggedin) {
        header('Location: welcome.php');
        exit;
    }
    else
        // If failed, you can note in a variable an echo in the html section
        $error = 'Login failed';
}

对于客户端验证,我建议使用jQuery Validate,它很简单并且运行良好。