Search code examples
phpsessionauthenticationprotected

Logged but can't access page for logged users?


I'm pretty noob in PHP but I'm trying to exercise. Since yesterday I'm on a problem I can't even understand, I thought my code was correct but it seems wrong

So here is my function to allow pages for logged users only

functions.php

function logged_only()
{
  if(session_status() == PHP_SESSION_NONE)
  {
      session_start();
  }
  if(!isset($_SESSION['auth']))
  {
      $_SESSION['flash']['danger'] = "You can't enter this page - not logged in";
      header('Location: login/login.php');
      exit();
  } 
}

So It's supposed to redirect me to login page if I'm not logged-in, simple

login.php

elseif(password_verify($_POST['password'], $user->password)){
    $_SESSION['auth'] = $user;
    $_SESSION['flash']['success'] = 'You're now connected';
    header('Location: ../profile.php'); // user's homepage
    exit();

There is some code above and under this, but it works pretty good.

So in this case the script should insert user's informations into his $_SESSION but it does nothing but redirect me at login.php. Also, the "profile.php" only contains "logged_only();" and a print_r (when I delete the redirection to login.php) of the $_SESSION, which shows nothing but "You can't access this page" (as I'm sending a message via $_SESSION)

Someone to guide me ? Thanks


Solution

  • You maybe should read about the session_start() in PHP: PHP Manual

    In short words: session_start() starts a new session or recovers the already existing session with the client.

    So after each redirect (also to your login.php) you need to call session_start().

    There is no need for

    if (session_status() == PHP_SESSION_NONE){
        session_start();
    }
    

    You should only use

    session_start();
    

    (In both, your functions.php and your login.php) before accessing the $_SESSION variable.

    functions.php

    function logged_only(){    
        session_start();
        if(!isset($_SESSION['auth'])){
            $_SESSION['flash']['danger'] = "You can't enter this page - not logged in";
           header('Location: login/login.php');
           exit();
        }
    }
    

    login.php

    session_start();
    // ... Rest of code
    elseif(password_verify($_POST['password'], $user->password)){
    $_SESSION['auth'] = $user;
    $_SESSION['flash']['success'] = 'You're now connected';
    header('Location: ../profile.php'); // user's homepage
    exit();