简体   繁体   中英

PHP - session redirecting me to infinite login.php page

So I have a header included in all of my website pages (including login.php) and in that header I placed the condition that if $_SESSION['logged'] is not set and not blank, it automatically redirects to login.php.

if(!(isset($_SESSION['logged']) && $_SESSION['logged'] != '')) {
        redirect_to(url_for('/login.php'));
    }

THE PROBLEM is that in my login.php file I don't have $_SESSION['logged'] set because it only sets after the user clicks on login and the file login.php redirects to itself infinite times before the page loads:

if($password == $user['hashed_password']) {
    $_SESSION['logged'] = $username;
    redirect_to(url_for('/staff/index.php'));
  }

The first code is in my header file and the second one in my login file. Login file includes header file.

Personally, I wouldnt include the redirect check on the login page at all, but if you do, you should avoid triggering the redirect condition when the user is already on the login page, for example, something like this should work:

$currentPage = basename($_SERVER['PHP_SELF']);

if($currentPage !== 'login.php' && empty($_SESSION['logged'])) {
    redirect_to(url_for('/login.php'));
}


// If they hit the login page but are already logged in, or submitted
// a valid password, log them in
// might need to adjust the "already logged in logic" for you use case
if(
    ($currentPage === 'login.php' && !empty($_SESSION['logged'])) ||
    $password == $user['hashed_password']
) {
    $_SESSION['logged'] = $username;
    redirect_to(url_for('/staff/index.php'));
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM