dqy92287 2017-03-17 13:18
浏览 66
已采纳

echo后无法取消设置会话变量

I have an error message stored in a session variable that I want to show only once. My method is to check if it's there, then echo it and unset it after.

<div class="signin">

  <form name="signuser" action="php/signin_user.php" onsubmit="return validateForm()" method="POST">
    <input type="text" name="email" placeholder="E-mail" value="<?php echo $_SESSION['signin']['email']; ?>"><br>
    <input type="password" name="password" placeholder="Password"><br>
    <input type="submit" value="Sign in">
  </form>

  <br>
  <div id="login-error" style="display: none"></div>
  
  <?php

  if(isset($_SESSION['msg']['signin-error'])) { 
      echo '<div id="login-php-error">';
echo '<p>'.$_SESSION['msg']['signin-error'].'</p>';
      echo '</div>';
}

  if(isset($_SESSION['msg']['signin-error'])) {
      unset($_SESSION['msg']['signin-error']);
  }

  if (isset($_SESSION['signin']['email']))
      unset($_SESSION['signin']['email']);

  ?>

</div>

I have tried with != "" as well:

<?php

  if($_SESSION['msg']['signin-error'] != "") {  
    echo '<div id="login-php-error">';
    echo '<p>'.$_SESSION['msg']['signin-error'].'</p>';
    echo '</div>';
  }

  if($_SESSION['msg']['signin-error'] != "") {
    unset($_SESSION['msg']['signin-error']);
  }

  if ($_SESSION['signin']['email'] != "")
    unset($_SESSION['signin']['email']);

?>

Nothing works. I have session_start() on all of my pages. It still shows up each refresh.

EDIT:

Obviously I am new to PHP and I see now that using session to give user feedback is silly. I ended up using GET to display error messages and it works great for my need. Thanks for the help!

</div>
  • 写回答

1条回答 默认 最新

  • dtnqbre7980007 2017-03-17 13:26
    关注

    Sessions are declared in the header. Headers are sent before any other content and echo'ing content/or just having text (e.g. HTML) will end the headers. That means you can't change sessions after echo'ing.

    There is however a way around using PHP output buffering. You use ob_start() at the start of your script and ob_end_flush() at the end. Using these functions you can edit sessions after echo'ing content.

    See this answer for more information.

    Edit:
    As @ccKep said you can still change the $_SESSION variable ($_SESSION['something'] = 'else') after sending the headers. You just can't start or destroy a session after the headers have been sent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集