Checking for a specific user - php

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

Related

Creating a website in PhpStorm and I'm having trouble checking a database variable

I have two functions, one to check whether a user is logged in, and another to check if the user is an admin. I also have a User database with one column named user_lvl, which displays fine if I output all the user data.
The problem I'm having is that with the admin function it doesn't seem read anything.
Here is the two functions code:
define('USER_LEVEL_ADMIN', '1');
// check whether a user session is active, return true if yes, else return no
function isLoggedIn() {
if (isset($_SESSION['userId'])) {
return true;
}
else {
return false;
}
}
// check whether user has required user level to access admin privileges, return true if yes
function isAdmin() {
// check if a user is in a session, then check if the users user_lvl is equal to 'USER_LEVEL_ADMIN
if (isset($_SESSION['userId']) && $_SESSION['userId'] && USER_LEVEL_ADMIN == $_SESSION['userId']['user_Lvl']) {
return true;
}
else { // works if you reverse true and false, else this is broke
return false;
}
}
And here is where it is being called:
<?php if (isLoggedIn() ) : ?>
<?php if (isAdmin() ) : ?>
<div>
Admin Panel
</div>
<?php endif; ?>
<div>
My Account
</div>
<?php endif; ?>
It displays 'My Account' but not 'Admin Panel'. Any help is much appreciated.
This code snippet is ment for testing and identify which function is gives this output
<?php
function isLoggedIn() {
return true;
}
function isAdmin() {
return false; // change it to true to see Admin Panel. You need to check the condition in this function.
}
if (isLoggedIn() ) :
if (isAdmin() ) :
echo '
<div>
Admin Panel
</div>';
endif;
echo '
<div>
My Account
</div>';
endif;
?>
The isAdmin() condition looks fine, You may echo out the session variable and crosscheck.
One of the 3 checks in the if statement is failing (returning false):
isset($_SESSION['userId']) basic isset check
$_SESSION['userId'] not sure what we're looking for here but this needs to result in boolean true
USER_LEVEL_ADMIN == $_SESSION['userId']['user_Lvl'] authorized privilege check
All 3 need to be true for the if to succeed.
if (isset($_SESSION['userId']) && $_SESSION['userId'] && USER_LEVEL_ADMIN == $_SESSION['userId']['user_Lvl']) {
return true;
}
else { // works if you reverse true and false, else this is broke
return false;
}
I suspect the if is false due to this: define('USER_LEVEL_ADMIN', '1'); which creates the named constant USER_LEVEL_ADMIN with a STRING value of '1'. Then, in your if statement you compare it to $_SESSION['userId']['user_Lvl']. Please check the variable type of $_SESSION['userId']['user_Lvl']. You can drop this line in your code to check that:
echo gettype($_SESSION['userId']['user_Lvl']);
It of course would need to match the type of USER_LEVEL_ADMIN which is string.

Admin And User Permission In 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;
}
}

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.

PHP navigating to page on login dependent on user role

I'm trying to direct users to specific pages once they have logged in, dependent on their role. I have the following code which logs in a user and directs them to the homepage, but doesn't consider their role:
public function login($context, $local)
{
if ($context->hasuser())
{ # already logged in
$local->message('message', 'Please log out before trying to login');
}
else
{
if (($lg = $context->postpar('login', '')) !== '')
{
$page = $context->postpar('page', '');
$pw = $context->postpar('password', '');
if ($pw !== '')
{
$user = $this->eorl($lg);
if (is_object($user) && $user->pwok($pw) && $user->confirm)
{
if (session_status() != PHP_SESSION_ACTIVE)
{ # no session started yet
session_start();
}
$_SESSION['user'] = $user;
$context->divert($page === '' ? '/' : $page); # success - divert to home page
}
}
$local->message('message', 'Please try again.');
}
else
{
$page = $context->getpar('page', '');
}
$local->addval('page', $page);
}
return 'login.twig';
}
I also have a function which checks if the user is a candidate:
public function hascandidate()
{
return $this->hasuser() && $this->luser->iscandidate();
}
I'm trying to get the system to direct the user to a page '/applyjob' if they are a candidate. Would anyone be able to help?
Cheers
I'm not sure where you are trying to load the page (are you using a framework?)
php's header() function may be what you are looking for.
http://php.net/manual/en/function.header.php
Without knowing exactly what hascandidate() returns and if your using any frameworks my best guess would be try adding this
if (hascandidate() == true) { $context->divert('/applyjob'); }
Right above this:
$context->divert($page === '' ? '/' : $page);

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