Infinite loop with $ _SESSION and redirect

1

What would be the best practices for maneuvering the following PHP code?

if(!isset($_SESSION['email'], $_SESSION['senha'], $_SESSION['nivel'], $logado)){
    header("location: index.php");
}

And of course when I kill the session it goes into an infinite loop for the simple fact that it does not exist. But how do I stop it from looping?

When I run the code the following screen appears:

    
asked by anonymous 22.05.2014 / 12:02

3 answers

4

If the problem is an include on all pages, just add one or more exceptions.

Example:

if( $_SERVER["PHP_SELF"] != '/index.php'
    && !isset($_SESSION['email'], $_SESSION['senha'], $_SESSION['nivel'], $logado)) {

   header("location: index.php");
}

suggestion not related to the problem: always use the full URL in the location if possible.

    
22.05.2014 / 17:28
3

You must have a set of pages that require the user to be logged in (for example: View Profile, Administrative Panel, Edit Article, etc.). For these do your if and redirect to a login.php page.

But you should also have pages that do not need a login to work (for example: Read Article, Login, Register). For these make the conditional only to modify elements of the page. If it is to read an article, check if the user is logged in and put his name there. Otherwise, put an "Enter" button. On these pages you will not redirect. This obviously includes the login page.

    
22.05.2014 / 12:09
0

Redirect to the authentication page ...

This part:

header("location: index.php");

Switch By:

header("location: login.php");

* login.php is an example. Of course, do not put the session check on the login page otherwise it will be in the same loop.

    
22.05.2014 / 15:40