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:16

Make sure a new session is created properly by first destroying the old session.

    session_start();
    // remove all session variables
    session_unset();
    // destroy the session
    session_destroy();
    session_start();
    $_SESSION['username'] = 'username';

Yes, session_start() is called twice. Once to call the unset and destroy commands and a second time to start a fresh session.

查看更多
君临天下
3楼-- · 2018-12-31 05:17

you should use "exit" after header-call

header('Location: http://www.example.com/?blabla=blubb');
exit;
查看更多
刘海飞了
4楼-- · 2018-12-31 05:17

I had the same problem and found the easiest way. I simply redirected to a redirect .html with 1 line of JS

<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>

instead of PHP

header_remove();
header('Location: admin_login.php');
die;

I hope this helps.

Love Gram

查看更多
看风景的人
5楼-- · 2018-12-31 05:17

Another possible reason:

That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.

It was worked!!!

I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!

查看更多
步步皆殇っ
6楼-- · 2018-12-31 05:19

Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...

查看更多
听够珍惜
7楼-- · 2018-12-31 05:21

If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.

session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
查看更多
登录 后发表回答