May
20
2013

Simple session based “flash” messages

Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.

Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better.  And as usual, where there’s a will, and some code- there’s a way!

Before we get started, make sure that a session is started, otherwise a) no message will be displayed, and b) super fun headers already sent messages.

//Ensure that a session exists (just in case)
if( !session_id() )
{
    session_start();
}

The rest is as easy as it gets!

The function

/**
 * Function to create and display error and success messages
 * @access public
 * @param string session name
 * @param string message
 * @param string display class
 * @return string message
 */
function flash( $name = '', $message = '', $class = 'success fadeout-message' )
{
    //We can only do something if the name isn't empty
    if( !empty( $name ) )
    {
        //No message, create it
        if( !empty( $message ) && empty( $_SESSION[$name] ) )
        {
            if( !empty( $_SESSION[$name] ) )
            {
                unset( $_SESSION[$name] );
            }
            if( !empty( $_SESSION[$name.'_class'] ) )
            {
                unset( $_SESSION[$name.'_class'] );
            }

            $_SESSION[$name] = $message;
            $_SESSION[$name.'_class'] = $class;
        }
        //Message exists, display it
        elseif( !empty( $_SESSION[$name] ) && empty( $message ) )
        {
            $class = !empty( $_SESSION[$name.'_class'] ) ? $_SESSION[$name.'_class'] : 'success';
            echo '<div class="'.$class.'" id="msg-flash">'.$_SESSION[$name].'</div>';
            unset($_SESSION[$name]);
            unset($_SESSION[$name.'_class']);
        }
    }
}

Setting messages

//Set the first flash message with default class
flash( 'example_message', 'This content will show up on example2.php' );

//Set the second flash with an error class
flash( 'example_class', 'This content will show up on example2.php with the error class', 'error' );

Displaying the messages

<?php flash( 'example_message' ); ?>
<?php flash( 'example_class' ); ?>

Conclusion

There’s no reason to sweat the small stuff, and hopefully this makes that possible for someone else!  I’ve wrapped the messages in a div by default, however, you can obviously get creative and implement this in any way necessary.

[dm]9[/dm]

10 Comments + Add Comment

  • Don’t you think using sessions to do this a bit a waste of resources?

    Why not implement something similar with cookies and JS and cut the persistent server-side storage out of the equation altogether?

    • I personally always prefer to avoid cookies, although you could certainly replace session usage with cookies and the end result would work just as well

  • I really love this its esactly what i wanted, how can i make it fade out and / or have an exit button to hide this flash message?

    • Try adding class=”fadeout-message”, then in your jquery scripts file (usually script.js in my case) add something such as:

      if('.fadeout-message'){
      setTimeout(function() {
      $('.fadeout-message').slideUp(1200);
      }, 5000);
      }

      • >how can i make it fade out
        .fadeOut()

        • Pretty easily! The following code needs to be inside a $(document).ready(function(){} statement:

          //NOTE: Make sure you include jquery or this will not work
          jQuery(document).ready(function($){
          if('.fadeout-message'){
          setTimeout(function() {
          $('.fadeout-message').slideUp(1200);
          }, 5000);
          }
          });

  • Thanks so much. This was very helpful.

  • Just the simple thing i’m looking for

  • This is absolutely genius! I love it.

    There is a tiny issue in the way this page parses your code block. It turned

    if( !empty( $message ) && empty( $_SESSION[$name] ) )

    into

    if( !empty( $message ) && empty( $_SESSION[$name] ) )

    The same issue is also in the final elseif condition.

    Thank you so much for this!!

  • Thank you sooo much , Just what i wanted!! tysm

Leave a comment