我试图阻止用户访问管理员和用户管理员使用的页面。现在,用户可以通过操纵URL导航到每个页面。
用户的角色在数据库中用1-3之间的数字确定,其中1表示管理员,2表示用户管理员,3表示用户。
我正在寻找的是一种解决方案,用户想要导航到的页面会检查登录用户的角色。如果导航的页面是为管理员准备的,则用户的角色号必须为1。如果用户没有访问该页面的权限,我希望他们的会话结束并返回登录页面。login.php
我试过一些解决方案,比如放
$_SESSION['role'] = $role;
{
//check if user if signed in
if($_SESSION['1'] == false)
{
echo 'Error. You do not have access';
}
}
die();
在每一页中。现在我没有得到任何错误的代码。但它也不起作用:/
感谢您的帮助!
<?php
//You can save user role in session like:
define('ADMIN_ACCESS', 1);
define('USER_ADMIN_ACCESS', 2);
define('USER_ACCESS', 3);
$_SESSION['role'] = ADMIN_ACCESS; // Admin (Any one of three)
$_SESSION['role'] = USER_ADMIN_ACCESS; // User Admin (Any one of three)
$_SESSION['role'] = USER_ACCESS; // User (Any one of three)
//On every page, add a variable which user role can access this page.
$requiredRole = ADMIN_ACCESS;
//Write a custom function to check user role.
function isAuthorized($requiredRole = NULL) {
if (session_id() == '') {
return FALSE;
}
if (isset($_SESSION['role'])) {
if ($_SESSION['role'] == ADMIN_ACCESS) {
return TRUE; // Administrator has access to every page/functionality.
}
if ($requiredRole < $_SESSION['role']) {
return FALSE;
}
}
return FALSE;
}
//And now, check if user can access the page or not by calling the function.
//On every page, add a variable which user role can access this page.
$requiredRole = ADMIN_ACCESS;
if (! isAuthorized($requiredRole)) {
// Redirect user as he is not autorized.
}
?>