PHP Session-Based Flash Messages

Flash Messages

As a web developer, you will no doubt have the need to display feedback to your users. There are several times when giving your users feedback is critical — When the user has submitted a form, entered incorrect login details, etc.

In the past, a common way of handling feedback like this was to append the data to the URL:

http://www.website.com?error=invalid_email

This method is not efficient for many reasons. For starters, you have to add some kind of message handler, usually in the form of long if/else or switch statements to any page where you want to display your messages. This method also clutters up the URL, and if not handled correctly, runs the risk of having your error messages/pages indexed by search engines.

A better way to handle messages

Many frameworks, and even some languages (eg: Ruby on Rails), include a way of handling messages that is often referred to as Flash Messages.These messages are usually stored in session data, and can therefore be retrieved on any page without the need of relying on complicated query strings and lengthy if/else statements.

Since almost every site that I work on has this same basic need of displaying messages to users then I’ve decided to create a simple, reusable, and easy to implement PHP Flash Messages class.

Download The Code

I’ve hosted the code on Github, so you can grab a copy there:

Git: git@github.com:plasticbrain/PHP-Flash-Messages.git

Source: https://github.com/plasticbrain/PHP-Flash-Messages

How to use

Before we begin, let’s look at what all comes in the box:

  • style.css – The CSS used to make the messages look pretty
  • class.messages.php – The main component; The actual class itself
  • README – A readme file that covers basic usage
  • images/ – a directory that holds the few images that we need
  • samples/ – a directory that contains a few samples of how to use this class

Begin by including the CSS style located at style.css. For optimization purposes, it’s best to add the code from this file to your existing CSS stylesheet.

Next, copy the images from images/messages/ to your images folder. Make sure that the CSS matches the path to these images.

The next, and possibly most crucial step, is to start a PHP Session. Without a Session, this script will not work:

<?php
if( !session_id() ) session_start();
...

Next, you need to include and instantiate the class:

...
require_once('class.messages.php');
$msg = new Messages();
...

Adding Messages

After the class is included and instantiated then you can start adding messages. In its current state, the class has four types of messages:

  • Success Message – ‘s’

    <?php $msg->add('s', 'This is a sample Success Message'); ?>
    

    Success Message

  • Error Message – ‘e’

    <?php $msg->add('e', 'This is a sample Error Message'); ?>
    

    Error Message

  • Warning Message – ‘w’

    <?php $msg->add('w', 'This is a sample Warning Message'); ?>
    

    Warning Message

  • Information Message – ‘i’

    <?php $msg->add('i', 'This is a sample Information Message'); ?>
    

    Information Message

Displaying Messages

On any page where you might want to display messages simply include the following code:

<?php echo $msg->display(); ?>

This will print all of the queued messages. If you want to print out a specific message type you can do so with the following code:

<?php echo $msg->display('e'); // only print error messages ?>
<?php echo $msg->display('s'); // only print success messages ?>
<?php echo $msg->display('i'); // only print information messages ?>
<?php echo $msg->display('w'); // only print warning messages ?>

Alternatively, you could include this code in a globally included file, such as a header or footer.

Checking for Errors (ie: form validation)

One of the greatest advantages of using this class is the ability to have a single system to manage messages across your entire site. To help integrate with common tasks, such as validating a form, there’s a built-in function — hasErrors() — that will return true if there are any error messages or false if not:

if( !isset($_POST['required_field']) ) {
     $msg->add('e', 'This field is required');
}

if( $msg->hasErrors() ) {
     // There ARE errors (the form is not valid)
} else {
     // There are NOT any errors (the form is valid)
}

Bonus: Closing the message boxes

With a few lines of jQuery you can easily give your users the ability to close the message boxes. The code that this class prints is already setup for this functionality, so you don’t need to edit any files. All you need to do to enable this functionality is include the following code inside your HTML <head> tags:

<!-- Include jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript"></script>

<!-- Code to close the message boxes -->
<script type="text/javascript">
$(function(){
     //---------------------------------------------------------------------------
     // Show the close icon when the user hover over a message  
     //---------------------------------------------------------------------------
     $('.messages').live('mouseenter', function(){
          $(this).find('a.closeMessage').stop(true, true).show();
     }).live('mouseleave', function(){
          $(this).find('a.closeMessage').stop(true, true).hide();
     });
     //---------------------------------------------------------------------------
     // Close the message box when the user clicks the close icon
     //---------------------------------------------------------------------------
     $('a.closeMessage').live('click', function(){
          $(this).parents('div.messages').slideUp(300, function(){ $(this).remove(); });
          return false;
     });
});
</script>

Future Plans

At this point, this class has pretty much everything I need. If I find the time, I may eventually add the functionality to handle jQuery Growl-style messages. Other than that, I don’t have any plans to improve this script.

The source code is available on Github, so please feel free to fork it!

Mike Everhart

Mike Everhart is a programmer, web developer, and owner of PlasticBrain Media LLC. He has a passion for startups and creating web-based applications to help them analyze, streamline, and automate their business processes. Mike has nearly 15 years of experience, and specializes in standards-based web design, programming, SEO, and SaaS.

14 Comments on "PHP Session-Based Flash Messages"

  1. SedeSickHeigh says:

    :)

  2. n0ta says:

    Looks great to expand any web app functionality. Thanks for sharing Mike.

  3. ChrisA says:

    Man, you Rock, i have spent hour googling and non till i found yout blog. thanks man. very helpgul. let me try it out. this is what i call bloging.

  4. ChrisA says:

    Hi Mike, can this session class be used in a MVC Framework? example: F3 (Fat Free Framework)

    • Mike Everhart says:

      I use a (slightly modified) forked version of this class in all of my Codeigniter projects, so it’s definitely possible to use it in an MVC framework. Unfortunately, I’m not familiar with the F3 framework, so I’m not sure what all it would take to integrate this class into it.

  5. ChrisA says:

    How can this messages be triggered using jQuery? I am corrently using another class design to show message and now using your class to show message incase no javascript enabled on the system. how can i use jQuery to enable the same error, if need be?

  6. Giovanni says:

    Hi Mike!
    Good job, but just one question: have you add the support for Growl?
    Thanks a lot!

    • Mike Everhart says:

      Thanks for the comments. I haven’t had the need for Growl messages, so I never integrated them. However, it shouldn’t be too hard to fork the code and add them yourself, if you’re feeling adventurous :)

  7. paul says:

    The code looks good! I couldn’t find the license under which you are distributing it in the github code. What license are you using?

  8. Eliza says:

    Beautifully done, and exactly what I was looking for! Thank you!!

Trackbacks for this post

  1. PHP | Pearltrees