PHP session lost after redirect

2018-12-31 04:49发布

How do I resolve the problem of losing a session after a redirect in PHP?

Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).

Update

I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.

28条回答
不流泪的眼
2楼-- · 2018-12-31 05:24
session_start();
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
if(!isset($_SESSION['name_session'])){
    unset($_SESSION['name_session']);
    session_destroy();
    }   
if(isset($_SESSION['name_session'])){
    $username = $_SESSION['name_session'];
    }
查看更多
刘海飞了
3楼-- · 2018-12-31 05:24

For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.

I could find it in the Apache error logs, though.

查看更多
不流泪的眼
4楼-- · 2018-12-31 05:25

If you're using Wordpress, I had to add this hook and start the session on init:

function register_my_session() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'register_my_session');
查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 05:26

This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:

session.use_cookies = 1 

I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.

查看更多
登录 后发表回答