douteng5673 2011-07-04 04:49
浏览 26
已采纳

PHP-修复问题,其中会话仅在刷新后生效

Please review this Stackoverflow post.

I have the same PHP problem as bob_cobb. Here's Brad Chrisite's answer:

Order of operations.

Place your session creation and test-for-validity check at the very top of the page so the rest of the page can make judgment calls off the existence of $_SESSION['username']

(Chances are you're trying to validate them inside the content area so your "yay" or "ney" message appears in the desired section of the document. Pretty, yes, but the whole top-half of the page can't see that it's [potentially] a valid session.)

He is basically saying that session_start() and the conditionals that check for session variables should be at the top, so that the rest of the page could act based upon that.

However, my session-check is at the top of the page.

<?php
session_start();

if ($_SESSION['username']) 
//User is already logged in, echo the log out button.
...    

else 
//User is not logged in, echo the log in form & button.
...    

//Login form validation if user is not logged in and submitted form.
//At the end, create session variable ($_SESSION['username'])

//Destroy session if user pressed log out button.
session_destroy();
?>

Everything works fine, but, as with the poster of the other question, I have to refresh my page, to get the top script executed (the script that checks for $_SESSION['username']).

Why is that?

  • 写回答

2条回答 默认 最新

  • duanhun3273 2011-07-04 04:57
    关注

    Do not echo anything before your entire control flow is finished. What I mean by this is that you should work to separate logic from display (even better: use a pattern like Model-View-Controller). In your case, maybe you can do something like this:

    <?php
    /* Place all your control logic at the beginning.
       Do not echo anything in this block. */
    
    session_start();
    
    if ($_SESSION['username']) {
      $loggedin = true;
    } else {
      $loggedin = false;
      ...    
    
      //Login form validation if user is not logged in and submitted form.
      //If login succeeded, set $loggedin to true.
      //At the end, create session variable.
    }
    
    //Destroy session if user pressed log out button.
      session_destroy();
    
    /* Only display logic below, we do not change any state here */
    
    if($loggedin) {
      echo logout button
    } else {
      echo login form
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系