Reputation: 3
I'm trying to prevent users from getting access to pages used by the admin and user-admin. Right now the user can navigate to every page by manipulating the URL.
The roles of the user is determined in the database with a number between 1-3 where 1 represents the Admin, 2 represents the user-admin and 3 represents the user.
What I'm looking for is a solution where the page that the user wants to navigate towards checks the logged in users role. If the navigated page is intended for the admin the user has to have role number 1. If the user does not have rights to the page I want their session to end and be sent back to the log in page. login.php
I've tried some solutions like putting
$_SESSION['role'] = $role;
{
//check if user if signed in
if($_SESSION['1'] == false)
{
echo 'Error. You do not have access';
}
}
die();
in each page. Right now I'm not getting any errors with that code. But it doesn't work either :/
Any help is appreciated!
Upvotes: 0
Views: 829
Reputation: 23958
<?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.
}
?>
Upvotes: 1