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!
Get Best Multi-Purpose WordPress Theme
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.
if( !session_id() )
{
session_start();
}
//Actual function
/**
function flash( $name = '', $message = '', $class = 'success fadeout-message' )
{
if( !empty( $name ) )
{
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;
}
elseif( !empty( $_SESSION[$name] ) && empty( $message ) )
{
$class = !empty( $_SESSION[$name.'_class'] ) ? $_SESSION[$name.'_class'] : 'success';
echo '
.$class.‘” id=”msg-flash”>’.$_SESSION[$name].‘
‘
;
unset($_SESSION[$name]);
unset($_SESSION[$name.'_class']);
}
}
}
//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' ); ?>
You can download the source from here
From: http://www.phpdevtips.com/
Extras: Addicted Upcoming