Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem unsetting a session variable

There's a form on my site that's used for inviting friends. It's a simple text field and a submit button. If there is an error I redirect back to this page and display an error message if their is a session variable set.

if (isset($_SESSION['invite_error'])) {
   echo $_SESSION['invite_error'];
   unset($_SESSION['invite_error']);
}

However, if I navigate away from this page and come back to it -the error message is still being displayed. If I navigate away and come back one more time it will be done. It's the same when I refresh that page...1 refresh won't get rid of it, but 2 will. I can't destroy the entire session, I just want to unset this one variable. PHP version is 5.2.5 build 6, register globals is off, I'm calling session_start() at the top of this page, I've tried using a no-cache header as well.

Edit: Added full code.

<?php 
ob_start();
session_start();

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];

if ($user_id==null) header("Location: /login.php");

if (isset($_SESSION['invite_errors'])) {

    $error = $_SESSION['invite_errors'];
    unset($_SESSION['invite_errors']);

}

require_once("ui/header.php");
?>



<div id="invite" class="content">

    <?php if($error) { ?>
        <div class="errors round">
            <?php echo $error ?>
        </div>
    <?php } ?>

    <h3>Invite Your Friends</h3>

    <div class="invite-form">
        <form method="post" action="controllers/invite.php">
            <div class="row">
                <textarea class="txt-area" name="emails" id="emails" rows="5"></textarea>
                <div class="tip">Separate multiple email addresses with ,</div>
            </div>
            <div class="row-submit">
                <input type="submit" name="submit" id="submit" class="submit-btn" value="Submit" />
            </div>
        </form>
    </div>

</div>

<?php
    require_once("ui/footer.php");
?>
like image 229
Seth Avatar asked Jun 22 '09 02:06

Seth


2 Answers

Start the session before you start the output buffering. So, switch the ob_start() and session_start() calls.

Since session cookies are defined in the headers sent to the browser, and headers are sent to the browser when you start the buffer, you must start the sessions before the buffer.

like image 114
James Skidmore Avatar answered Nov 15 '22 05:11

James Skidmore


The example you provided should work. Perhaps some kind of session cache is getting in your way. You could try modifying your code as follows:

if (isset($_SESSION['invite_errors']) && $_SESSION['invite_errors']) {

    $error = $_SESSION['invite_errors'];
    $_SESSION['invide_errors'] = false;
    unset($_SESSION['invite_errors']);

    // Explicitly write and close the session for good measure
    session_write_close();

}
like image 34
Sander Marechal Avatar answered Nov 15 '22 06:11

Sander Marechal