PHP in Action Rotating Header Image

Flash messages

Redirects are useful in web programming, especially when implementing the Post-Redrect-Get pattern. But there is a problem with redirects: there is no simple way to send a message to the user across the redirect. When processing a GET request, you can display whatever messages you want. The most simplistic way is to echo them directly; or if just slightly more sophisticated, set it in the template that’s about to become the web page. When processing a POST request that is to be followed by a redirect, you can’t do that. The response (redirect) sent back to the browser does not have any text or HTML content. In practice, it just contains the URL of the page you’re redirecting to. If you try echoing the message, it will cause the redirect to fail because you sent content before the header that signals redirect.

So how to get the message displayed? The simplest way to do it would be to include it in the URL:

header('Location: http://www.example.com/index.php?message='.urlencode($message));

It’s possible, but your URLs can get very long and you might find it silly:

http://www.example.com/index.php?message=This+is+a+message+to+demonstrate+how+long+a+URL+can+get+when+you+put+long+strings+into+it [/code]

The more common choice is to keep the message in session and make sure it's removed from session after it's been displayed. That's what flash messages do. In military terminology, a flash message is defined as:

A category of precedence reserved for initial enemy contact messages or operational combat messages of extreme urgency.

I don't like a name that could be confused with Adobe Flash, so when I implemented my version of this, I looked up "flash" in the thesaurus and decided to call them flares instead.

Here are a couple of examples I've picked up.

Zend Framework:

$flashMessenger = $this->_helper->FlashMessenger;
$flashMessenger->setNamespace('actionErrors');
$flashMessenger->addMessage($message);

CakePHP (from http://labs.iamkoa.net/2008/01/13/session-based-flash-messages-look-better-cakephp/):

$this->Session->setFlash('Your post has been saved.');
$this->redirect('/news/index');

In my own work, I've done it in a slightly different way by letting the redirect object hande the flash/flare and returning the redirect object from the action method, somewhat like this:

return Redirect::toAction('settings')->addFlare('Settings changed');

I don't necessarily claim that it's better than the others, but it makes sense to have alternatives.

This article was originally posted with an incorrect timestamp, and has been updated to the current time as of June 2.

Share/Save/Bookmark

8 Comments

  1. Shaun says:

    I love using Flash messages. It makes life so much easier. I have never used them in the Zend Framework but use them a lot in CodeIgniter. Is very easy to do. In CodeIgniter they call them Flashdata and can be found in the session object.

    http://codeigniter.com/user_guide/libraries/sessions.html

  2. Tomek says:

    Good thing to do is using a unique id for each message to avoid problems with multiple windows/tabs.
    Something like that in ZF:

    $flashId = md5(uniqid());
    $flashMessenger = $this->_helper->FlashMessenger;
    $flashMessenger->setNamespace($flashId);
    $flashMessenger->addMessage($message);

    $this->_redirect($url . ‘/flashId/’ . $flashId);

    if ($this->getParam(‘flashId’)) {
    $flashMessenger = $this->_helper->FlashMessenger;
    $flashMessenger->setNamespace($this->getParam(‘flashId’));
    $msgs = $flashMessenger->getMessages();
    }

  3. Johny says:

    I never had the idee of giving out the error or status somewhere in code mostly defined them in template or language file and printed them out, but this way is also interesting.
    But the method with get variable seems very vulnerable

    ?message=(url encoded html code with link to my viagra site)

    I still think the messages should not be defined inside the php code, just id identifier of messages in a text definition or language file

  4. Kenrick says:

    I created a really simple flash class for when I ported web.py to php. You can find the class here:
    http://code.google.com/p/webpy-php-port/source/browse/trunk/webphp/lib/flash.php

    its really simple to use and uses $_SESSION data similar to many other classes.

    Flash::add(‘notice’, ‘your message’);

    then retrieve it after the request:
    if($msg = Flash::get(‘notice’)) {
    echo $msg;
    }

    I find the flash pattern to be really helpful.

  5. dagfinn says:

    @Tomek: Yes, the unique ID is exactly what I’ve done too. Web apps should be safe for “power users”. I’ve had some ugly experiences with some that weren’t, even losing data sometimes.

  6. Horde has had this thing only recently dubbed “flash messages” for years – you get a $notification object, and you can push as many notices onto it as you want, with different message levels. When you want to display them, you pull them off the stack. It’s not limited to the absolute next request; they stay there until you need them. And because of the more general architecture you can use it for things like calendar alarms, also, which we do – alarms even have custom output that lets you snooze or dismiss them.

  7. dagfinn says:

    That’s interesting. I’ve noticed that Zend Framework also has a more general approach, though perhaps not as general as this.

    It seems like a good idea as long as it doesn’t make the API too complex for the application programmer.

  8. [...] of HTTP is with sessions. There is a pattern that takes advantage of this called a “flash message“. The basic idea is to store a value in a session when the form is submitted, and to echo it [...]

Leave a Reply