PHP页面限制访问级别的访问

时间:2018-04-03 22:53:55

标签: php mysql

在MySQL表中我有:

  1. ID
  2. 用户名
  3. 密码
  4. 水平
  5. 等级"管理员" =访问所有页面
    等级"用户" =仅访问某些页面

    <小时/> 在auth.php页面(包含在每个页面中)。

    session_start();
    if(!isset($_SESSION["username"])){
        header("Location: login.php");
        exit(); 
    }
    

    在登录页面中我有:

    session_start();
    
    // If form submitted, insert values into the database. 
    if (isset($_POST['username'])) {
    
        $username = stripslashes($_REQUEST['username']); // removes backslashes
        $username = mysqli_real_escape_string($conn, $username); //escapes special characters in a string
        $password = stripslashes($_REQUEST['password']);
        $password = mysqli_real_escape_string($conn, $password);
    
        //Checking is user existing in the database or not
        $query = "SELECT * FROM `users` WHERE username='$username' and password='" . md5($password) . "'";
        $result = mysqli_query($conn, $query) or die(mysql_error());
        $rows = mysqli_num_rows($result);
        if ($rows == 1) {
            $_SESSION['username'] = $username;
            header("Location: index.php"); // Redirect user to index.php
        } else {
            header("Location: login.php"); // Redirect user to index.php;
        }
    };
    

    我应该如何制作两个会话,会话为&#34; admin&#34; &#34; user&#34;的会话,所以每个页面都有不同的访问级别?

1 个答案:

答案 0 :(得分:0)

试试这个!

  $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";

    if ($result = $mysqli->query($con,$query)) {


        while ($row = $result->fetch_assoc()) {
         $_SESSION['username'] = $row["username"];
         $_SESSION['level'] = $row["level"]);
        }

        $result->free();
    }

当页面需要某个级别时,只需验证级别是否正确。