Why is my SESSION array OK on one page but empty on another?

核能气质少年 提交于 2019-11-29 13:09:36

Any ideas?

Yes. You have to learn to debug your code.
As you can see, your question cannot be answered out of guesswork. So, it's time for handwork.

  • First make sure you can see any error occurred. Just add an intentional one and see. If you see no errors you have to turn it on.
  • then make a testing script to see if your sessions do work

    <? 
    session_start(); 
    if (!isset($_SESSION['counter'])) $_SESSION['counter']=0;
    echo "Refreshed ".$_SESSION['counter']++." times.<br>
    <a href=".$_SERVER['PHP_SELF'].'?'.session_name().'='.session_id().">refresh</a>"; 
    ?>
    

if it works, make it to use cookies

<? 
session_start(); 
if (!isset($_SESSION['counter'])) $_SESSION['counter']=0;
echo "Refreshed ".$_SESSION['counter']++." times.<br>
<a href=".$_SERVER['PHP_SELF'].">refresh</a>"; 
?>

if it works too, you have to check your code.
Print out variables, reduce code, etc

Try comparing the session ids. If you get a different session id across the calls, the session management is not correctly set up.

I.e. your code may rely on session ids stored in cookies, but that option is disabled (see your php.ini).

As a debugging measure you may use "transparent session ids" (they're concatenated to any link), but not for production code.

Based on your first code block, it sounds like you might be calling session_start() after you've tried to set the $_SESSION variables. You must call session_start() first! I could be wrong, in which case I apologise. But based on the above code snippet it could well be your problem!

If you're calling session_close() where you should be, then are you accidentally destroying the session? Perhaps a few too many session_destroy() calls?

And by a few too many I mean one.

Make sure that:

  1. You execute session_start() before you set or get a session variable. (If the server is configured to autostart sessions, this is not necessary.)
  2. Both scripts live on the same (sub)domain. (It's not enough for pages to be on the same server to share a session, they also have to belong to the same (sub)domain.)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!