user5224574
user5224574

Reputation:

Flash messages with sessions in PHP

I work on a project in PHP which does not use any kind of a framework for PHP. I come from Yii background and I've used:

Yii::app()->user->setFlash('flash_name', 'Flash value');

And checked it with:

Yii::app()->user->hasFlash('flash_name');

To check if it is present and if it exists, and to get the value of it I used:

Yii::app()->user->getFlash('flash_name', 'Default Flash value');

For now, I wrote these functions to set, check and get flash:

function set_flash($flash_name, $value) {
    $_SESSION['flashes'][$flash_name] = $value;
}

function has_flash($flash_name) {
    return isset($_SESSION['flashes'][$flash_name]) ? true : false;
}

function get_flash($flash_name, $default_value = null) {
    if(has_flash($flash_name)) {
        return $_SESSION['flashes'][$flash_name];
    }

    return $default_value;
}

However, when I use it in my post.php like this:

set_flash('success', true);

And check it in my index.php like this:

<div class="container">
    <?php if(has_flash('success') && (get_flash('success') === true)): ?>
        <div class="alert alert-success">
            <h4>Success!</h4>
            <hr />
            <p>You have successfully posted new content on your website. Now you can edit or delete this post.</p>
        </div>
    <?php endif; ?>
</div>

whenever I refresh the page, the message would still appear there.

How can I remove the flash after it's been used or invoked?

Upvotes: 2

Views: 111

Answers (1)

Alex Tartan
Alex Tartan

Reputation: 6826

Add a new line to get_flash:

function get_flash($flash_name, $default_value = null) {
    if(has_flash($flash_name)) {
        $retVal = $_SESSION['flashes'][$flash_name];
        // don't unset before you get the vaue
        unset($_SESSION['flashes'][$flash_name]); 
        return $retVal;
    }

    return $default_value;
}

Upvotes: 2

Related Questions