在PHP中检查用户是否为admin

时间:2015-05-12 08:01:08

标签: php mysql admin

我对php很新,我正在尝试做我的学校作业,但老师只是说" google it"而且我真的找不到适合我的asnwer。

这是我的login.php(请原谅其中的瑞典笔记,这些是给我老师的)

<?php  //Start the Session
session_start();
require('connect.php');
//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['password'])){
//Sätter form värderna i variabler
$username = $_POST['username'];
$password = $_POST['password'];
//Kollar om variblerna redan finns i databasen
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";

$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
//Kollar om bägge värdena är likadana i databasen och sedan skapar sessionen om de är det.
if ($count == 1){
$_SESSION['loggedin'] = 1;
$_SESSION['username'] = $username;
}else{
//3.1.3 Om värdena inte stämmer kommer ett fel medelande att skickas till användaren.
echo "Invalid Login Credentials.";
}
}
//Om han loggar in så skickas han vidare till protected.php
if ($_SESSION['loggedin'] == 1) {
header('Location: protected.php');
}else{
?>

此处是您登录后访问的页面(受保护的页面)

<?php

    session_start();
    require('connect.php');
    // startar sessionen så att man kan använda session variablerna
    // Inkluderar connect.php för att ansluta till databasen


    if ($_SESSION['loggedin'] != 1) {
        //Om loggedin är inte lika med 1 skickas han till första login sidan

        header('Location: index.php');
        exit;
    }

?>
<html>
<head><title>Logged in!</title></head>
<body>ASDSDFSDF<br><a href="logout.php">Log out</a><br>
<?php
    $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
    $result = mysql_query($sql); 
    $admin = mysql_fetch_array($result);
    $_SESSION['admin'] = $admin['admin'];
    if ($_SESSION['admin']) == 1 {
    echo "You are an Admin!";
    }else{
    echo "You are a normal user";
    }
?>
</body>
</html>

我不明白这段代码是如何运作的。 :/

 <?php
        $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
        $result = mysql_query($sql); 
        $admin = mysql_fetch_array($result);
        $_SESSION['admin'] = $admin['admin'];
        if ($_SESSION['admin']) == 1 {
        echo "You are an Admin!";
        }else{
        echo "You are a normal user";
        }

4 个答案:

答案 0 :(得分:2)

请再次检查此代码:

$sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";

这里可能有两个错误:

  1. 您无法在'';
  2. 中插入$ _SESSION
  3. 在引用时,“$ _SESSION ['username']”应更改为“$ _SESSION [username]”;
  4. 总结一下,您可以使用以下方式:

    $sql = "SELECT admin FROM `user` WHERE username='".$_SESSION['username']."'";
    

    通过这种方式,您可以保留具有引号的SQL的原始方法:

    WHERE username='xxx'
    

答案 1 :(得分:0)

试试这段代码:

$sql = "SELECT admin FROM user WHERE username='".$_SESSION['username']."'"; //  username='".$_SESSION['username']."'"   instead username='$_SESSION['username']'";

$result = mysql_query($sql); 
$admin = mysql_fetch_array($result); 

$_SESSION['admin'] = $admin['admin']; 
if ($_SESSION['admin'] == 1) {  // Be carefull you had if($_SESSION['admin']) == 1 {  leaving "1" outside of the if
echo "You are an Admin!"; 
}else{ 
echo "You are a normal user"; 
}

注意:告诉老师她是时候停止教mysql了,而是教mysqli或PDO

答案 2 :(得分:0)

不要担心mysqli和其他评论,这段代码适用于学习目的。这是逐行解释的:

    $sql = "SELECT admin FROM `user` WHERE username='$_SESSION['username']'";
    $result = mysql_query($sql);

执行sql查询,搜索存储在session ['username']中的用户名的用户。它不会获取所有列,只有admin列,它表示用户是admin还是isnt。

    $admin = mysql_fetch_array($result);

这只是将sql结果加载到数组中。如果找到具有存储用户名的用户,则它将只是一个包含一个布尔变量的数组:1或0

    $_SESSION['admin'] = $admin['admin'];

将布尔变量存储到会话

    if ($_SESSION['admin']) == 1 {
        echo "You are an Admin!";
    }else{
        echo "You are a normal user";
    }

打印操作结果。

但有几点需要注意。例如,如果用户名不存在会发生什么。如果您收到一些错误,请尝试打印所有内容并发送错误消息。

答案 3 :(得分:0)

您的代码不安全,因为:

  • 您可以注射(mySql Injection)
  • 您的密码以纯文本格式存储

此外,我建议您使用MVC模式。

<强>的login.php

<?php
session_start();
require("functions.php"); // file with your functions

if ($_SESSION["logged"]) // if already logged, redirect to admin page 
    header("Location: ./admin.php");
else
{
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // logIn function in "functions.php" file, returns true if correctly logged
        $login = logIn($_POST["user"], $_POST["password"]);
        if ($login === true)
        {
            $_SESSION["logged"] = true;
            header("Location: ./admin.php");
        }
        else
        {
            // login failed, show error page

            $error = $login;
            // html code for header
            require("templates/header.php"); 

            // html code for body that will display $error
            require("templates/error_page.php"); 

            // html code for last part of the page
            require("templates/footer.php");
        }
    }
    else
    {
        // No POST request, so the user must fill the form yet

        require("templates/header.php");

        // Contains html code for login form
        require("templates/login_form.php");

        require("templates/footer.php");
    }
}
?>

functions.php (用于存储php函数的文件):

function logIn($username, $pass)
{
    if ($username == "" || $pass == "")
        return "Please, fill every text field.";
    $pdo = connectToServer();

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");    
    $stmt->execute(array("username" => $username));

    $fetch = $stmt->fetch();

    $numberRows = $stmt->rowCount();
    if ($numberRows > 0)
    {
        // user exists, check for password
        $crypted = hash('ripemd160', $fetch["salt"] . $pass);
        /* NOTE: you must have encrypted passwords in the same way 
           at the moment of signing up.
           Without encryption (not recommendable) you can use:
           $crypted = $pass;
        */

        if ($crypted == $fetch["pass"])
        {
            // Logged, do whatever you want and return true
            return true;
        }
        else
            return "You have inserted a wrong username or password";
     }
     else
         return "You have inserted a wrong username or password";   
}