PHP $_SESSION empty after header redirect

2020-04-11 05:00发布

I'm losing the data in $_SESSION when I do a header redirect. When I walk through this with a debugger I can see all my data in $_SESSION before I exit();

Login.php :

...

if($result == 1){       
    header("Location: /myaccount.php");
    session_write_close();
    exit();
} else {
    header("Location: /login.php?invalid=yes");
    exit();
} 

Then I put a breakpoint after the session_start() conditional below and $_SESSION is completely empty.

myaccount.php:

<?php
if(!isset($_SESSION['user_id'])) { session_start(); }

$docRoot = getenv("DOCUMENT_ROOT");
...

Where did my session go?

3条回答
小情绪 Triste *
2楼-- · 2020-04-11 05:30

Make sure you are using the function session_start(); before the if-statement on myaccount.php

查看更多
▲ chillily
3楼-- · 2020-04-11 05:31

You should call session_start() on every page accessing (that is, reading or writing) $_SESSION, and call it before any access to the session array. So, be sure you call session_start() on both pages.

查看更多
Ridiculous、
4楼-- · 2020-04-11 05:36

Yes don't delete post ... I had EXACTLY the same issue, and this post caused me to involuntarily smack palm firmly against forehead. And it fixed the problem (with my code that is, not my dumbness). Cheers!

查看更多
登录 后发表回答