tags:

views:

749

answers:

4

Hi, I have a class called User with static function loginRequired(), which returns false if the user is logged in and true if the user is logged out. It also appends an error to an error class that I created that tells the person using the site that they must be logged in to view the content.

The idea is that for the top of each function that would require the user to be logged in, we write this code:

if(User::loginRequired()) return;

Which will output the error and immediately return from the function. I would rather do this, however:

User::loginRequired();

And return from the calling function inside of the loginRequired function... but because loginRequired() is in a separate class in a separate file, this won't work. Is it possible to return from the function that calls loginRequired(), within loginRequired()?

Thanks.

+5  A: 

I'm not sure you can do exactly what you want, however, you might want to look at using exceptions. This would allow you to throw an exception in the User::loginRequired function and catch it at some higher level. You could also look at using the exit() PHP function.

Brian Fisher
+3  A: 

The way I've seen a number of open source apps handle this is by having a require_login() function which performs a redirect should the user not be logged in.

nickf
A: 

Is the content WITHIN the actual page dynamic? What I mean is, do I need to authenticate just to see anything other than the login page, or do I see some things when I'm logged in and other things when I'm not, etc? Because if the entire directory/section of the server is behind a log-in screen you could just add something to the .htaccess file of the directory that redirects anyone not logged in, etc.

On the other hand, you could have that file holding the login status included into whatever page/script that the user is viewing, with the included file returning just the login status instead of its entire contents. This is covered under includes under Example 5, "include() and the return() statement". If you did this, you could use a ternary condition like:

$logged_in = (include('userlogin.php') == TRUE) ? TRUE : FALSE;

And then in each protected function have something like:

global $logged_in;

You are still stuck with an IF clause wrapping the entire function, but at least you have the login status. If you wanted to get rid of the IF inside of the function, you could always make calling the function conditional. Like:

$content = ($logged_in == TRUE) ? some_function() : redirect_User();

Then again, I just started learning this stuff 2 months ago and still don't understand classes and objects, so I could be way off base.

Anthony
A: 

OT: I would consider changing the method's name to isLoggedIn() if your described purpose is the only one. A method called loginRequired() would be better off protecting confidential content.

chelmertz