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 如何让子窗口鼠标滚动独立,不要传递消息给主窗口
  • ¥15 dy网页ck不扫码解决方法
  • ¥15 如何能达到用ping0.cc检测成这样?如图
  • ¥15 关于#DMA固件#的问题,请各位专家解答!
  • ¥15 matlab生成的x1图不趋于稳定,之后的图像是稳定的水平线
  • ¥15 请问华为OD岗位的内部职业发展通道都有哪些,以及各个级别晋升的要求
  • ¥20 微信小程序 canvas 问题
  • ¥15 系统 24h2 专业工作站版,浏览文件夹的图库,视频,图片之类的怎样删除?
  • ¥15 怎么把512还原为520格式
  • ¥15 MATLAB的动态模态分解出现错误,以CFX非定常模拟结果为快照