Most efficient way to check if user is logged in and then...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Markto
Forum Newbie
Posts: 22
Joined: Thu Nov 17, 2011 1:13 pm

Most efficient way to check if user is logged in and then...

Post by Markto »

What is the most efficient way to check if user is logged in and then display different information for each state? I am currently using an if/else statement, but this seems a bit messy, because there is a ton of code under the else.

Example:

Code: Select all

if(isset($_SESSION['idmember']))
{
//the pages code.
} else {
echo "you must be logged in";
}
as you can probably tell, this can lead to a very long if statement, and it can get a bit confusing. I was wondering if there was a better way to check if a user is logged in without including all of my code in an if else statement.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Most efficient way to check if user is logged in and the

Post by Celauran »

You could always just reverse the order...

Code: Select all

if (!isset($_SESSION['whatever']))
{
    // They need to login
}
Markto
Forum Newbie
Posts: 22
Joined: Thu Nov 17, 2011 1:13 pm

Re: Most efficient way to check if user is logged in and the

Post by Markto »

But that would still nest all of my code in this big "if" statement. I was hoping there was some more elegant way of solving this problem, like checking to see if the user is logged in, and if not, just quitting (exit() maybe?), and then having all of the code follow this if statement, which I could include at the top of every relevant page.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Most efficient way to check if user is logged in and the

Post by Celauran »

Markto wrote:But that would still nest all of my code in this big "if" statement.
How so? The existing if redirects them if they aren't logged in. No need for any additional conditionals.
Markto
Forum Newbie
Posts: 22
Joined: Thu Nov 17, 2011 1:13 pm

Re: Most efficient way to check if user is logged in and the

Post by Markto »

I think you are right. My mistake! :) I misinterpreted your code. Thanks for going easy on me - I appreciate the help.
Post Reply