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

如何根据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);

我有一个基于PHP / MySQL的网站,其中包含用于管理页面的成员页面和文件夹的文件夹。 我想根据他们登录的方式将用户引导到不同的页面 - 作为成员或管理员(来自主用户页面) - 这是我尝试过的功能,但它不起作用。 p>

如何编写适合此功能的函数? p>

  function connectadmin($ level){
 if($ level ===“ 管理员“){
 include('admin / home.php'); 
} elseif($ level ===”Member“){
 include('member / home.php'); 
} 
  } 
 
connectadmin($ level); 
  code>  pre> 
  div>

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();

}