PHP: session isn't saving before header redirect

后端 未结 10 1256
死守一世寂寞
死守一世寂寞 2020-12-06 17:26

I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database. My code is as f

相关标签:
10条回答
  • 2020-12-06 18:04

    Have you got an session_start(); on the top?

    Not tested but cant you do something like this:

    session_start();
    $_SESSION['userID'] = $user->id;
    if( $_SESSION['userID'] == $user->id )
    {  
        header('Location: /index.php');
    }
    

    I never have this Problem before, interesting

    0 讨论(0)
  • 2020-12-06 18:05

    This was annoying as hell but I finally figured out a solution.

    config.php i had: include 'session.php';

    At the top of session.php, I had: session_start();

    By moving session_start() to the top of the config.php file, viola...

    Problem solved!

    0 讨论(0)
  • 2020-12-06 18:06

    I had the same problem recently. I'm writting a customized MVC Website for school and, as everyone told, start_session() must be written in the very first lines of code.

    My problem was THE LOCATION of "session_start()". It must be the first lines of your global controller, not the first lines of the view. $_SESSION was not accessible in controller's files because it was only initiated when the server render the view.

    Then, I'm using session_write_close() after the header('location: xxx.php') call to keep session variables for the next request.

    ex:

    globalController.php :

    //First line
    session_start();
    require_once('Model/Database.php');
    require_once('Model/Shop/Client.php');
    ...
    

    logonController.php:

    ...
    //Users is validated and redirected.
    $_SESSION['client'] = $client;
    header('location: index.php');
    session_write_close();
    

    Hope it solved your problems.

    0 讨论(0)
  • 2020-12-06 18:09

    I know this is an old toppic but I found the solution (for me). I've put a exit after the header.

    $_SESSION['session'] = 'this is a session';
    header('location: apage.php');
    exit;
    

    This works for me

    0 讨论(0)
提交回复
热议问题