Infinite loop with $_SESSION and redirect

Asked

Viewed 901 times

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 it’s obvious that when I kill the session it loops into an infinite loop for the simple fact that it doesn’t exist. But, how do I stop it from looping?

When I run the code the following screen appears: Esta página da web tem um loop de redirecionamento

  • Whatever the code of index.php, it has the same if, if you have only take it solves ?

  • Although you have already received several answers, missed to say something that to do it I need to know what would be the variable $logged

  • plus a var for when the email is checked it initializes it with the value 1 if the process has worked

3 answers

4

If the problem is a 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 Location, if possible.

3

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

But you should also have pages that don’t need login to work (for example: Read Article, Log in, 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 a button "enter". On these pages you will not redirect. This obviously includes the login page.

  • In case the only pages that are accessed without the user being logged in are the Login pages. I’m not sure how to do the correct check. In fact the only thing I want with this question is to check whether the user is logged in or not...

  • 1

    @Luitame But you already have a parole that makes the check. Only seven a variable to true when the user is logged in and use it to change things in the interface.

0

Redirect to the authentication page...

That part:

header("location: index.php");

Exchange for:

header("location: login.php");

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.