douxi8119 2015-02-26 11:01
浏览 32
已采纳

如何根据PHP中的会话数据将用户重定向到不同的目录?

I have a PHP/MySQL based website with folders for member pages and folders for admin pages. I want to direct the users to the different pages according to how they login - as a member or as a admin (from the main user pages) - this is the function I've tried and it doesn't work.

How can I write a function that will work for this?

function connectadmin($level) {
    if ($level === "Administrator"){
        include('admin/home.php');
    }elseif ($level === "Member"){
        include('member/home.php');
    }
}

connectadmin($level);
  • 写回答

1条回答 默认 最新

  • dongzai3139 2015-02-26 11:02
    关注

    Well, you should redirect your users, not include files:

     // At beggining of this file insert this line
     // Start session
     session_start();
    
    function connectadmin($level) {
        if ($level === "Administrator"){
    
            // Set user role
            $_SESSION['role'] = 'Administrator';
    
            // Redirect user
            header('Location: admin/home.php');
            exit();
        }elseif ($level === "Member"){
    
            // Set user role
            $_SESSION['role'] = 'Member';
    
            // Redirect user
            header('Location: member/home.php');
            exit();
        }
    }
    
    // $level should be something you retrieve from your Database for example
    // And perhaps, should be 'Administrator' or 'Member' following your example
    connectadmin($level);
    

    And after redirect user don't forget to validate if the logged in user have access to the redirected page.

    Edit: For example, if you want to validate if user is Administrator and have access to the page admin/home.php, do something like this:

    // You should get from your database, some file or use sessions, 
    // in your function I have used sessions, so lets use them here too
    
    // At beggining of your file use this
    session_start();
    
    // If user is not Administrator
    if($_SESSION['role'] !== 'Administrator'){
    
        // It's not admin, let redirect him to somewhere else or show him a Access not allowed page
        header('Location: accessNotAllowed.php');
        exit();
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c