Jump to content

BAD WAY? Is "else" more secure?


ChenXiu
 Share

Go to solution Solved by Phi11W,

Recommended Posts

Which is better?

if(!isset($_SESSION['user'])) {
exit;
}
if($_SESSION['user'] !== 'SiteOwner') {
exit;
}

- or -

if(!isset($_SESSION['user'])) {
exit;
} else {
if($_SESSION['user'] !== 'SiteOwner') {
exit;
}
}

Is the "if else" version more secure?
Basically, if nobody's logged in, exit immediately. But if somebody's logged in, make extra sure it's the Site Owner.
p.s. I know that " if( !isset($_SESSION['user'] || ($_SESSION['user'] !== 'SiteOwner')) { exit; } " works, but I want to keep the code flexible for adding other types of users in the future.

Thank you.

Edited by ChenXiu
Link to comment
Share on other sites

  • Solution

Over the lifetime of this (or any other) Application, you will spend far more time reading its code than you will writing any of it so go for whichever form expresses your intention most clearly. 

Personally, I'd go with the former or, perhaps, an even more concise one: 

if ( ! isset( $_SESSION['user'] ) ) 
   exit ; 
if ( 'SiteOwner' !== $_SESSION['user'] )
   exit ; 

I'm not sure of the context in which this runs - perhaps a redirect to another page might be more appropriate than the "exit"?  YMMV. 

Regards, 
   Phill  W.

 

  • Great Answer 1
Link to comment
Share on other sites

2 hours ago, ChenXiu said:

Is the "if else" version more secure?

Either way works. Once the exit language construct executes, the script stops. It won't do anything with that next if construct when the "user" SESSION variable isn't set. So using else, in this case, is unnecessary. More information about how exit works can be found here:
https://www.php.net/manual/en/function.exit.php

With that said, if using "else" makes more sense to you...you might consider "elseif"

if(!isset($_SESSION['user'])) {
    exit;
} elseif($_SESSION['user'] !== 'SiteOwner') {
    exit;
}

And when you get to the stage of blocking multiple user types, you could potentially do something like this:

if(!isset($_SESSION['user'])) {
    exit;
} elseif(in_array($_SESSION['user'], array('SiteOwner', 'SiteAdmin'))) {
    exit;
}

Note that the above code is untested.

Edited by cyberRobot
Added examples
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.