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

Make sure session_write_close is not called between session_start() and when you set your session.

session_start();

[...]

session_write_close();

[...]

$_SESSION['name']='Bob'; //<-- won't save
查看更多
牵手、夕阳
3楼-- · 2018-12-31 05:12

I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.

Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:

function sessionKill(){

    session_destroy();

}

to:

function sessionKill(){

    session_destroy();
    session_start();

}

And everything worked!

查看更多
看淡一切
4楼-- · 2018-12-31 05:12

I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.

So don't forget that!

查看更多
浪荡孟婆
5楼-- · 2018-12-31 05:13

I had the same problem. I worked on it for several hours and it drove me crazy.

In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.

查看更多
妖精总统
6楼-- · 2018-12-31 05:15

I fixed by giving group write permissions to the path where PHP store session files. You can find session path with session_save_path() function.

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 05:16

I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.

I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.

signin.php

if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);

signin_action.php

<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {

echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}

?>

It is not a beautiful work-around but it worked.

查看更多
登录 后发表回答