PHP: session isn't saving before header redirect

后端 未结 10 1356
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题