为我的 PHP 会话分配角色


Assign Roles to my PHP Session?

目前,我有一个php脚本来检查用户是否已登录。如果是,页面将加载。如果不是,它将重定向到登录页面。我已经实现了,但是现在,我只想允许具有特定角色的用户能够查看页面,而不仅仅是登录。在phpro_auth数据库中的phpro_users表中,我添加了一个名为"角色"的附加列。例如,我希望分配了"管理员"角色的用户能够查看页面。总之,我正在尝试修改我的脚本,该脚本当前检查要登录的用户,以检查角色。我怎样才能做到这一点?我的脚本如下:

<?php
/*** begin the session ***/
session_start();
if(!isset($_SESSION['user_id']))
{
    $message = header("Location: http://localhost/correspondence/prologin/index.php");
}
else
{
    try
    {
        /*** connect to database ***/
        /*** mysql hostname ***/
        $mysql_hostname = 'localhost';
        /*** mysql username ***/
        $mysql_username = 'root';
        /*** mysql password ***/
        $mysql_password = '';
        /*** database name ***/
        $mysql_dbname = 'phpro_auth';

        /*** select the users name from the database ***/
        $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
        /*** $message = a message saying we have connected ***/
        /*** set the error mode to excptions ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        /*** prepare the insert ***/
        $stmt = $dbh->prepare("SELECT phpro_username FROM phpro_users 
        WHERE phpro_user_id = :phpro_user_id");
        /*** bind the parameters ***/
        $stmt->bindParam(':phpro_user_id', $_SESSION['user_id'], PDO::PARAM_INT);
        /*** execute the prepared statement ***/
        $stmt->execute();
        /*** check for a result ***/
        $phpro_username = $stmt->fetchColumn();
        /*** if we have no something is wrong ***/
        if($phpro_username == false)
        {
            $message = 'Access Error';
        }
        else
        {
            $message = 'Welcome '.$phpro_username;
        }
    }
    catch (Exception $e)
    {
        /*** if we are here, something is wrong in the database ***/
        $message = 'We are unable to process your request. Please try again later"';
    }
}
?>

由于您添加了新列,因此您应该获得新值:

`$stmt = $dbh->prepare("SELECT phpro_username, phpro_auth  FROM phpro_users WHERE phpro_user_id = :phpro_user_id);`

然后使用

if($row = $stmt -> fetch_assoc()) {
  if($row['phpro_auth'] == 'admin') {
    $massage = 'Welcome ,'.$row['phpro_username'];
  } else {
    $massage = 'Not authorized';
} else {
  $massage = 'Access Error';
}

向用户反馈他无法访问您的网站的原因。我的代码中的第一个 if 语句将执行与你相同的操作。

你只需要检查表中对应的值,看看它是否返回一个管理员用户...

if($phpro_username == false && $phpro_rol == "admin")//or the correct data to be returned...
        {
            $message = 'Access Error';
        }