PHP isset $_session equal to string - php

So guys I'm new to PHP OOP
I make Login with Roles, and make function(checkrole) for knowing what role it is.
This is how my function looks like
public static function hasadmin()
{
if(session_id() == '') {
session_start();
}
if(isset($_SESSION['role']) == 'A') {
return true;
}
}
and call it into navbar partial :
<?php if (helper::login() == true && helper::hasadmin() == true) { ?>
<li style="float:\right">Logout</li>
<li>Petugas</li>
<li>Laporan</li>
Function helper::login works perfectly.
Every time I login with another role the partial (petugas, laporan)
still comes out.

isset returns a boolean. Run the isset and check the actual value.
if(isset($_SESSION['role']) && $_SESSION['role'] == 'A') {

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.

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

two if statements in php

I have two seperate if statements, the first if statement is not working but the second one is.
The first if statement works on my other pages and I am unsure of how to properly code this as I am a beginner to PHP.
<?php
session_start();
if($_SESSION['loggedin'] != 'true') {
header("location:login.php");
}
if ($_SESSION['admin']=='N') {
header("location:errorpage.php");
}
?>
What is true in your conditions? It can be bool type or string type.
If You set like this:
$_SESSION['loggedin'] = TRUE;
$_SESSION['loggedin'] = 'true';
You have got two different variable sets.
You can compare it using == or === to include variable type.
For example:
$_SESSION['test_1'] = TRUE;
$_SESSION['test_2'] = 'true';
var_dump( $_SESSION );
array(2) { ["test_1"]=> bool(true) ["test_2"]=> string(4) "true" }
$_SESSION['loggedin']?
Why don't just clear every SESSION var on logout and if the SESSION vars are set => the user is logged in.
And use after the header(); an exit();
Try var_dump($_SESSION['loggedin']) and edit your question.
Or maybe your loggedin var is not a string but a boolean so you could do if(!$_SESSION['loggedin'])
Try using Boolean values rather than strings. I would also use a const for the admin variables. I would do the following;
$_SESSION['loggedin'] = true/false;
$_SESSION['admin'] = true/false;
public class Priviledges
{
public CONST Admin = 0;
public CONST User = 1;
public CONST Contributor = 3;
//change this to however you want to do it :)
public static function isAdmin($val)
{
if ($val == Priviledges::Admin)
{
return true;
}
else
{
return false;
}
}
}
then when you set the admin session variable you can go;
$_SESSION['admin'] = Priviledges::Admin;
if(!$_SESSION['loggedin'])
{
header("location:login.php");
exit()
}
else if (!Priviledges::isAdmin($_SESSION['admin']))
{
header("location:errorpage.php");
exit()
}
else
{ //do your stuff if none of these conditions are met.. }
Always add an exit() or die() after sending a "Location" HTTP header:
<?php
session_start();
if($_SESSION['loggedin'] !== 'true') {
header("location:login.php");
exit();
}
if ($_SESSION['admin'] === 'N') {
header("location:errorpage.php");
exit();
}
Check: php - Should I call exit() after calling Location: header?.
From aaronsaray blog:
Remember, just because the browser is smart enough not to show the
content, doesn’t mean that this isn’t dangerous. So, it’s a little
less dangerous say if this page is just showing a user search option
or some information. It is much more dangerous if this is a page that
executes an action. This is because the entire PHP page will execute
if you don’t put a die() statement.
On other cases, if you want a condition to be evaluated only when a previous condition is false, you may use a "else if".

$_SESSION never getting set

I'm working on an assignment on a PHP course, and I'm stucked at the last part of it.
The assignment is to create a simple login form and use a session as well as hardcoded usernames and passwords (i.e. no db).
What I have problems with is the class that handles the login, and sessions especially. There's a lot of code and I didn't know what I could remove and therefore I've put it on Pastebin instead, hope that's alright.
Thing is that the unit tests that's built into the class passes except for nr. 4, the one that's checking that the user is logged in. The problem seems to be that $_SESSION[$this->loginSession] doesn't get set, and this is what I need help with.
The variable $loginSession is declared in the beginning of the class, and should be set to "isLoggedIn" when a user types a correct username and password, but that doesn't happen (no error message).
My class is:
<?php
class LoginHandler {
private $loginSession;
public function IsLoggedIn() {
if($_SESSION[$this->loginSession] == "isLoggedIn") {
return true;
}
else {
return false;
}
}
public function DoLogin($username, $password){
if ($username != null && $password != null){
switch ($username){
case "hello";
if ($password == "1234"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
case "hello2";
if ($password == "12345"){
$_SESSION[$this->loginSession] == "isLoggedIn";
return true;
}
else return false;
}
}
else {
return false;
}
}
public function DoLogout(){
unset($_SESSION[$this->loginSession]);
}
public function Test() {
$this->DoLogout();
// Test 1: Check so you're not logged in.
if($this->IsLoggedIn() == true){
echo "Test 1 failed";
return false;
}
// Test 2: Check so that it's not possible to login with wrong password.
if ($this->DoLogin("hello", "4321") == true){
echo "Test 2 failed";
return false;
}
// Test 3: Check that it's possible to log in.
if ($this->DoLogin("hello", "1234") == false){
echo "Test 3 failed";
return false;
}
// Test 4: Check that you're logged in
if ($this->IsLoggedIn() == false){
echo "Test 4 failed";
return false;
}
return true;
}
}
?>
I hope it's enough to include the class and not all the other files, otherwise I'll put them up.
Now I see it :-)
$_SESSION[$this->loginSession] == "isLoggedIn";
== should be =
== compares while = sets
You need to start the session. session_start(); Place it at the very top of the documents (only one time on a page load) you are using.
$this->loginSession is never set so it's NULL
$_SESSION[null] is not possible as far as i know
change your code to
private $loginSession = 'testing';
and it should work
Why do you put semicolon in your case instruction case "hello";There should be a colon. case "hello": { ...instructions}

Check if another function is declared, otherwise change location

I've got a "make-do" page authenticator which defines what usergroups are allowed to access that page, however, some of my scripts allow the user to pass if that page is, say, his user edit page but not touch any other users edit page. For that, I disabled access to the usergroups except if you're an admin or the user edit page you are currently on is your own.
I tried to create a function to do this, but the allowOnly usergroups function deals out the punishment without checking to see if the other function is defined elsewhere on the page.
Here's the "make-do" functions and an example of how I'd like them to work:
public function allowOnly($officer, $administrator, $superuser)
{
$authority = 0;
if ($officer == true && $this->session->isOfficer()) {
$authority++;
}
elseif ($administrator == true & $this->session->isAdmin()) {
$authority++;
}
elseif ($superuser == true & $this->session->isSuperuser()) {
$authority++;
}
if ($authority != 0) {
return true;
}
else {
header("Location: ../incorrectRights.php");
exit;
}
}
function allowCurrentUser()
{
global $authority;
$authority++;
}
This changes the users location if they're not any of the allowed usergroups, but since that code is executed before "allowCurrentUser", it changes the location before the function gets the chance to allow the user through.
I'd like it to work like this:
<?php
include("functions.php");
$functions->allowOnly(false, false, true);
if($session->username == $allowedUserName) {
$functions->allowCurrentUser();
}
I'm sorry if I'm not descriptive enough, or my code lacks efficiency, heck, even if I've missed a built-in php function which does this for me!
you should check out PHP's function_exists(), this will tell you wether or not the function already exist.
you have some error in your code too.
$administrator == true & $this->session->isAdmin()
should be
$administrator == true && $this->session->isAdmin()
as you have used only single & whereas it should be &&
and also change
$superuser == true & $this->session->isSuperuser()
to
$superuser == true && $this->session->isSuperuser()
after reading your code, i realized you are using $authority variable to hold the value and to check wether to authorize user or not. and plus you are using global. i would never have done that way, instead i would declare $authority as class property below is the example of how you could do it.
class functions
{
//declare class propert and set default value to 0
protected $_authority = 0;
public function allowOnly($officer, $administrator, $superuser)
{
if ($officer == true && $this->session->isOfficer()) {
$this->_authority++;
}
elseif ($administrator == true && $this->session->isAdmin()) {
$this->_authority++;
}
elseif ($superuser == true && $this->session->isSuperuser()) {
$this->_authority++;
}
if ($this->_authority != 0) {
return true;
}
else {
header("Location: ../incorrectRights.php");
exit;
}
}
public function allowCurrentUser()
{
$this->_authority++;
return $this->_authority;
}
}
UPDATE:
instead of redirecting the page why not return false and redirect during function call, you can do it this way.
class functions
{
//declare class propert and set default value to 0
protected $_authority = 0;
public function allowOnly($officer, $administrator, $superuser)
{
if ($officer == true && $this->session->isOfficer()) {
$this->_authority++;
}
elseif ($administrator == true && $this->session->isAdmin()) {
$this->_authority++;
}
elseif ($superuser == true && $this->session->isSuperuser()) {
$this->_authority++;
}
return ($this->_authority != 0) ? true : false;
}
public function allowCurrentUser()
{
$this->_authority++;
return $this->_authority;
}
}
and while in function call.
include("functions.php");
if($functions->allowOnly(false, false, true)) {
//person is allowed access
}
//else allow current user
elseif($session->username == $allowedUserName) {
$functions->allowCurrentUser();
}
else {
//redirect here
header("Location: ../incorrectRights.php");
exit;
}
I'm not completely certain if this is the answer you are looking for based on the title but this is what I get the impression you are asking for.
Assuming what happens is that your check against allowOnly() takes the user to the "../incorrectRights.php"-page before you've checked if the user logged in is the same as the page looked at, what you need to do is put the check inside the allowOnly function or at least before you do the check for $authority != 0.
Here's a quick example of how you could solve this:
public function allowOnly($officer, $administrator, $superuser)
{
$authority = 0;
if ($officer == true && $this->session->isOfficer()) {
$authority++;
}
elseif ($administrator == true && $this->session->isAdmin()) {
$authority++;
}
elseif ($superuser == true && $this->session->isSuperuser()) {
$authority++;
}
if(function_exists('allowCurrentUser')){
if (allowCurrentUser()) {
return true;
}
}
if ($authority != 0) {
return true;
}
else {
header("Location: ../incorrectRights.php");
exit;
}
}
function allowCurrentUser()
{
if($session->username == $allowedUserName){
return true;
}
else {
return false;
}
}
Then your useage would result in something more like
<?php
include("functions.php");
$functions->allowOnly(false, false, true);
?>
As you can see I also threw in the function_exists('functionnamehere') call that seems to be requested in the question title, since we actually declare the function and therefore know it exists you could also just do this:
if ($authority != 0 || allowCurrentUser()) {
return true;
}

Categories