PHP Returning from a function to another file

I have a class called User with a static function loginRequired () that returns false if the user is logged in and is true if the user is logged out. It also adds an error to the error class 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 every function that will require a user to log in, we write this code:

if(User::loginRequired()) return;

      

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

User::loginRequired();

      

And return from the calling function inside the loginRequired function ... but since 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 () to loginRequired ()?

Thank.

0


source to share


4 answers


The way I've seen a lot of open source apps deal with this is a function require_login()

that does a redirect if the user isn't logged in.



+3


source


I'm not sure if you can do exactly what you want, however you might want to use exceptions . This will allow you to throw the exception in the User :: loginRequired function and catch it at a higher level. You can also use the PHP exit () function.



+5


source


Is WITHIN content actual dynamic? I mean, do I need to authenticate just to see anything other than the login page, or do I see some things when I am logged in and other things when I am not, etc. ? Because if the entire server directory / section is outside the login window, you can simply add something to the directory's .htaccess file that redirects everyone who is not logged in, etc.

Alternatively, you can have this file containing the login status included in whatever page / script the user is viewing, and the included file only returns the login status and not all of its content. This is described in the includes in example 5, the "include () and return () statement". If you have done that, you can use a 3D condition like:

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

      

And then in every protected function there is something like:

global $logged_in;

      

You're still sticking with the IF clause wrapping the whole function, but at least you have the login status. If you want to get rid of the IF inside a function, you can always call the function conditionally. How:

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

      

Then I started studying this stuff again 2 months ago and still don't understand classes and objects, so I might be out of base.

0


source


OT: I would consider changing the method name to isLoggedIn () if your described purpose is the only one. A method called loginRequired () will better protect sensitive content.

0


source







All Articles