如何根据 PHP 中的会话数据将用户重定向到不同的目录?
How can I redirect users to different directories based on session data in PHP?
我有一个基于 PHP/MySQL 的网站,其中包含用于成员页面的文件夹和用于管理页面的文件夹。我想根据用户的登录方式将用户引导至不同的页面 - 作为会员或管理员(从主用户页面) - 这是我尝试过的功能,但它不起作用。
我如何编写适用于此的函数?
function connectadmin($level) {
if ($level === "Administrator"){
include('admin/home.php');
}elseif ($level === "Member"){
include('member/home.php');
}
}
connectadmin($level);
嗯,你应该重定向你的用户,而不是包含文件:
// 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);
并且在重定向用户之后不要忘记验证登录用户是否可以访问重定向的页面。
编辑:例如,如果您想要验证用户是否为管理员并有权访问页面 admin/home。php,请执行以下操作:
// 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();
}
我有一个基于 PHP/MySQL 的网站,其中包含用于成员页面的文件夹和用于管理页面的文件夹。我想根据用户的登录方式将用户引导至不同的页面 - 作为会员或管理员(从主用户页面) - 这是我尝试过的功能,但它不起作用。
我如何编写适用于此的函数?
function connectadmin($level) {
if ($level === "Administrator"){
include('admin/home.php');
}elseif ($level === "Member"){
include('member/home.php');
}
}
connectadmin($level);
嗯,你应该重定向你的用户,而不是包含文件:
// 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);
并且在重定向用户之后不要忘记验证登录用户是否可以访问重定向的页面。
编辑:例如,如果您想要验证用户是否为管理员并有权访问页面 admin/home。php,请执行以下操作:
// 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();
}