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'); ?>
- Error Message – ‘e’
<?php $msg->add('e', 'This is a sample Error Message'); ?>
- Warning Message – ‘w’
<?php $msg->add('w', 'This is a sample Warning Message'); ?>
- Information Message – ‘i’
<?php $msg->add('i', 'This is a sample 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!
Looks great to expand any web app functionality. Thanks for sharing Mike.
My pleasure! I hope you find it useful.