douchun1900 2014-10-30 22:07
浏览 38
已采纳

如果会话isset和变量==,则仅显示页面

i'm trying to add roles for certain pages on a small internal site i am running.

i assign the following sessions when user logs into the site login form;

// Register $username, $role Sessions and redirect
$_SESSION['username']= $username; 
$_SESSION['accessLevel'] = $role;
$_SESSION['is_logged_in'] = true;

i then have the following on my logout.php page;

<?php 
session_start();
session_destroy();
header("Location: ../login.php");
?>

i want to restrict page based on the users $_SESSION['accessLevel']

for instance only show page if $_SESSION['accessLevel'] == 'admin' else redirect to login page (or error page)

here is what i have on an admin page;

<?php
session_start();
if (!isset($_SESSION['username']) && $_SESSION['accessLevel'] == 'admin'){ 
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
 <p>ADMIN AREA!! </p>
 <p>username: <?php echo $_SESSION['username'];?></p>
 <p>Access: <?php echo $_SESSION['accessLevel'];?></p>
</body>
</html>
<?php
}
else {
    header("location:../login.php");
}
?>

now the page redirects to login.php when i login using admin credentials if i remove the check i print_r the sessions are correct;

$_SESSION['accessLevel'] = admin

$_SESSION['username'] = testuser

where am i going wrong?

  • 写回答

1条回答 默认 最新

  • douyeke2695 2014-10-30 22:10
    关注

    You want the username to exist, right now you are checking to see if it is not isset(). Update your conditional to:

    if(isset($_SESSION['username']) && $_SESSION['accessLevel'] == 'admin') { 
        // HTML here
    } else {
        header("location:../login.php");
    }
    

    Also, a side note: if you ever have an edge case were you set a username value but not a accessLevel value, you will get a fatal error with this conditional. You should be making sure that the accessLevel is set to be safe:

    isset($_SESSION['username'], $_SESSION['accessLevel']) && $_SESSION['accessLevel'] == 'admin'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集