CrazeD
CrazeD

Reputation: 535

PHP How to implement flash messages

I'm working on a small custom CMS and would like to implement flash messages. I have searched for hours, but I can't find anything that behaves the way I want. And I can't seem to make anything work.

I want to be able to pass a variable (via $_SESSION) to another page and, on that next request, it will be removed. I want to be able to use a keep_flash function, in case I don't want the message to be removed with the next server request.

Can anyone send me in the right direction? I can't really make anything work.

Thanks.

EDIT: Here is some code I am playing with. It sort-of works. When you first visit the page, it sets the $_SESSION and everything is fine. But if you refresh, now it deletes the $_SESSION. If you refresh again, it adds it back...etc. So, if you were to visit the page, refresh, then go to another page the flash message wouldn't be in the $_SESSION. So how can I fix this?

class flash
{
private $current = array();
private $keep    = array();

public function __construct()
{
    if (isset($_SESSION['flash'])) {
        foreach($_SESSION['flash'] as $k=>$v)
        {
            $this->current[$k] = $v;
        }
    }
}

public function __destruct()
{   
    foreach ($this->current as $k=>$v)
    {           
        if (array_key_exists($k,$this->keep) && $this->keep[$k] == $v) {
            // keep flash
            $_SESSION['flash'][$k] = $v;

        } else {
            // delete flash
            unset($_SESSION['flash'][$k]);
            unset($this->current[$k]);
            unset($this->keep[$k]);
        }           
    }
}

public function setFlash($key,$value)
{
    $_SESSION['flash'][$key] = $value;
}

public function keepFlash($key)
{
    $this->keep[$key] = $this->getFlash($key);
}

public function getFlash($key)  
{       
    if (array_key_exists($key,$this->current)) return $this->current[$key];

    return null;
}   
}

Upvotes: 1

Views: 4181

Answers (1)

bensiu
bensiu

Reputation: 25604

basic idea is to have script always check specific variable in session (usually called 'flash') for content - if not empty display and delete it from session. When message is needed just place is same variable in session and next check would pick it up....

keep_flash in your case would not proceed with delete, or move to other place based on your needs.

for implementation just google it - usually it wrapped in some kind of class - I personally like phpclasses.org or part of framework

Upvotes: 3

Related Questions