使用会话授予用户对页面的管理权限


Using sessions to grant user admin to page

我正在为一个制作简单多页网站的班级做一个练习。其中一个页面"addeddit.php"页面要求用户是管理员。然而,如果网站的用户是经纪人,那么他们应该被拒绝访问此页面。

我不确定如何正确编码"addedit.php"页面。

我保存了一个数据库,用户名和密码以及"Y"或"N"(如果他们是管理员)。我的登录页面的php如下所示,我添加了$isadmin变量。

到目前为止,我的"addedit.php"代码如下:session_start();

<?php
session_start();
if($isadmin==true){
header("location:addedit.php");
exit;
}
else
{
echo "Sorry, you must be an administrator to view this";
}
}
?>

一旦尝试,请设置类似的会话

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

在主页和"addedit.php"中尝试如下。。

<?php
        session_start();
        if($_SESSION['admin'] == 'Y'){
        header("location:addedit.php");
        exit;
        }
        else
        {
        echo "Sorry, you must be an administrator to view this";
        }
        }
        ?>

在登录用户的页面中,您应该将值存储在会话中,例如

$_SESSION['userid'] = $userid;
$_SESSION['isadmin'] = $isadmin;

然后在addedit.php页面上,您需要从SESSION对象中检索值,例如

$isadmin = $_SESSION['isadmin'];

此外,如果您在$isadmin中存储的是"Y"标志,请务必对照该标志进行检查,例如

if ($isadmin == 'Y')

在此处更改类似的代码

$fetchresult = $result->fetchRow();
$userid = $fetchresult['username'];
$_SESSION['isAdmin'] = $fetchresult['admin'];
header("location:mainpage.php");

现在,添加edit.php

<?php
    session_start();
  if(isset($_SESSION)){
    if($_SESSION['isAdmin'] == true){
      header("location:addedit.php");
      exit;
    }
   else    {
      echo "Sorry, you must be an administrator to view this";
    }
 }
?>

更改else语句

else
{
    $fetchresult = $result->fetchRow();
    $userid = $fetchresult['username'];
    $isadmin = $fetchresult['admin'];
    if($isadmin=='N' || $isadmin='Y')//As you mention in the question 
            //That admin column of two value one is N and one is Y
     $_SESSION['admin']=$isadmin;
    header("location:mainpage.php");
}
?>

现在您的addedit.php如下

<?php
session_start();
$_SESSION['admin']=$isadmin;//Only added this line
if($isadmin==TRUE){//rest of the code remain same. i  change only true to 
    //TRUE. But it should work with true as well
header("location:addedit.php");
exit;
}
else
{
echo "Sorry, you must be an administrator to view this";
}
}
?>