Search code examples
phphtmlsessionunset

Cannot unset session variable after 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!


Solution

  • 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.