Admin And User Permission In PHP - php

So i am making my own website and also im new in php code im just beginning with it i have a problem how do i disable user with a role as a "User" and cannot visit "Admin" pages only with "Admin" role can visit and use it. What will be my PHP code with this problem? i saw some code but i really having problem understanding it because im just new in PHP code.
here is my code that i use in my problem
server.php
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
but user role is still able to access admin/home.php
also in admin/home.php i have this code
home.php
if (!isLoggedIn()) {
$_SESSION['msg'] = "You must log in first";
header('location: ../errors-404.html');
}
this is the function of isLoggedIn
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}

You can add user type checking in your isLoggedIn()-function:
function isLoggedIn($type = null)
{
if (!isset($_SESSION['user'])) {
// We got no session at all. Not logged in.
return false;
}
$currentType = $_SESSION['user']['user_type'] ?? null;
if ($type && $type != $currentType) {
// We got a type passed to the function, but the session type
// doesn't match
return false;
}
// Either we got no type or the type matched.
return true;
}
Now you can use it for checking if a user is logged in at all (by omitting the argument) or if the user has a specific role (by passing the role to the function):
To check if a user is logged in at all:
// In the top of the page you want to protect
if (!isLoggedIn()) {
// Not logged in at all
header('location: foo.php');
exit;
}
To check if a user is logged in with a specific role:
// In the top of the page you want to protect
if (!isLoggedIn('admin')) {
// Not logged in as an admin
header('location: bar.php');
exit;
}

Because you are just checking if the $_SESSION['user'] is set or not and it's set in both cases.
Check it as:
function isAdmin()
{
//this checks is user is logged in and type == "admin"
return (isset($_SESSION['user']) && isset($_SESSION['user_type']) && ($_SESSION['user_type']=="admin") );
}
Conceptually there should be another function like this
function validateLogin(){
if(isLoggedIn()){
if(isAdmin()){
//redirect to admin page
}
else{
//redirect to user page
}
}
else{
// invalid login
}
}
And on the top of your .php files for admin, use the same function to validate if the user has access to that particular page or not.

You need to change the below function on admin page.
function isLoggedIn()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin') {
return true;
}else{
return false;
}
}

Related

Simple User Registration & Login Script in PHP and MySQLi

Hello I use the code below for my login system and I was wondering if someone can help me I'm trying to add an admin features so it will show a link saying admin and if there not an admin then it will disable the link.
http://www.allphptricks.com/simple-user-registration-login-script-in-php-and-mysqli/
Make database field something like user_role or name it however you want but use it to store user role/privilege.
After user is logged in store data from that field to session and perform conditional check.
if (isset($_SESSION['user_role'] && $_SESSION['user_role'] === 'admin')
{
// user have admin privilege
}
Create function for sake of reusability.
function isAdmin()
{
if (isset($_SESSION['user_role'] && $_SESSION['user_role'] === 'admin')
{
return true;
}
return false;
}
Usage:
if (isAdmin()) {
echo 'You are admin!';
}
This is just example, name your session and function however you want.
Best regards.
After the login the username is stored in $_SESSION['username'].
So I think something like this should do the trick:
if ($_SESSION['username'] === 'admin') {
echo 'admin';
} else {
echo 'admin';
}
When you have an extra field in your user table, lets call it 'group', and this field is filled with the group name 'admin' you can fill this group name in the session at this point of the login script:
$rows = mysqli_num_rows($result);
if($rows==1){
$row = mysqli_fetch_assoc($result);
$_SESSION['username'] = $username;
$_SESSION['group'] = $row['group'];
// Redirect user to index.php
header("Location: index.php");
}'
and later in the code check the session with $_SESSION['group'] instead of $_SESSION['username'], like above.

Checking for a specific user

I have the following code which makes sure that the user is logged in. But I want to change to code to check for a specific user id. Can anyone help me with this?
function protect_page() {
if (logged_in() === false) {
header('Location: protected.php');
exit();
}
}
You could update your login function with an extra optional variable.
If you don't specify the $user_id variable it will take the value 0, which will only check if the user is logged in. If you do specify a certain $user_id then the function will return true if the user is logged in and the $user_id matches the id stored in the session.
function logged_in($user_id = 0)
{
return (isset($_SESSION['user_id']) && (($user_id == 0) || ($_SESSION['user_id'] == $user_id))) ? true : false; //this function checks if the user is logged in and matches the given user identifier.
}
You can modify your function logged_in and pass the specific user id to the function:
function logged_in($id) {
//this function checks if the user is logged in and has a specific id
return (isset($_SESSION['user_id']) && $_SESSION['user_id'] === $id) ? true : false;
}
You have to change your protect_page function to fit the new logged_in function:
function protect_page() {
if (logged_in(7) === false){
header('Location: protected.php');
exit();
}
}

Mage::getSingleton('admin/session')->getUser() is returning null

I have a custom module in my magento (version 1.5) and it's meant to load the currently logged in admin username like this in one of my controller:
$current_user = Mage::getSingleton('admin/session')->getUser();
if ($current_user) {
$this->current_user = $current_user->getUsername();
} else {
$this->current_user = '';
}
When the code runs, $this->current_user is empty, so I did a var_dump($current_user); exit(); and it appears to be null akways (even if I am logged in).
Any ideas why this might be?
Mage::getSingleton('core/session', array('name'=>'adminhtml'));
//verify if the user is logged in to the backend
if(Mage::getSingleton('admin/session')->isLoggedIn()){
echo "Admin Logged in";
}
else
{
echo "You need to be logged in as an admin.";
}

Trying to create a difference between admin login and user login

if($_SESSION['userid'] == 1)
{
$_SESSION['admin'];
header('location:admin.php');
}
else if ($row = mysqli_fetch_assoc($result)) {
$_SESSION['user'] = $username;
header('location:logoutpage.php');
} else {
header('location:login.php');
}
What I'm trying to achieve is allowing the admin to have a session called admin and a user having a session called user.
During creation of the session add one variable $_SESSION['userType']='admin'; for admin and similarly $_SESSION['userType']='user'; for normal user.

Check if a User is Logged On In a PHP Login System

I'm relatively new to PHP and have been making a PHP login system. It works fine and all, but I'm wondering if there's a cleaner and more efficient way to check if a user is logged in. At the current moment my code looks like this:
session_start();
if(isset($_SESSION['username']))
{
Echo "*Whole bunch of HTML*";
}
else{
header("location:index.php");
end();
}
I want to make it to where the if statement checks if the user is logged in and nothing more, rather than having the if statement check if the user is logged in then displaying the page within in the if statement. Is this possible?
You are doing things ok. But here is what I do for my code:
function checklogin() {
if (!$this->isLoggedIn())
return false;
else
return true;
}
function isLoggedIn() {
if (isset($_SESSION['user_id']) && isset($_SESSION['user_email'])) {
if( !$this->isTimeOut() )
return false;
$where = array(
'id' => $_SESSION['user_id'],
'email' => $_SESSION['user_email']
);
//this is database class method
$value['data'] = $dataBaseClass->login_access($where);
if ($value['data'] != FALSE && $_SESSION['user_id'] == $value['data']->id && $_SESSION['user_email'] == $value['data']->email) {
return true;
}
/*
username or userlevel not exist or s_ecryption session invalid
User not logged in.
*/
else
return false;
}
/**
* cookie check for user login || you can escape this
*/
else if (isset($_COOKIE['cookie_key']) && $_COOKIE['cookie_key'] != '') {
$cookie_key = $_COOKIE['cookie_key'];
$where = array(
'cookie_key' => $cookie_key
);
$user_data = $databaseClass->login_access($where);
if (!empty($user_data)) {
$_SESSION['user_id'] = $user_data->id;
$_SESSION['user_email'] = $user_data->email;
return true;
}
} else {
return false;
}
}
Make a library/functions file, write above code, include that file in class files you need and call the function.
Hope this helps.

Categories