PHP how to handle user flash messages via session

flash messages via session

Handle user flash messages via session variables which is more professional and easy to manage, How we can display these messages in traditional way, developers know how they display messages and update users about status of user operation(s) like

  • record save successfully
  • record updated successfully
  • Failed to create account, please try after a while

Most of new developers manage these kind of messages by sending the whole message in get variable, or some code for message like true for success message and false for error message.

like in the following example we have to redirect from add.php to index.php while sending message from add.php and displaying message on index.php

At top on index.php page right after body tag

the above method of displaying messages is ok but not good and professional, we can improve our messaging system by sending the message in session variable instead of query string ($_GET variable)
that has the following advantages

  1. User can not alter the message
  2. Message can be removed after displaying, means on refresh user will not be seeing same message stick over there.
  3. Its professional way of doing it

How to handle user flash messages via session

In above add.php to index.php scenario, we will set a session variable $_SSESSION[‘msg’] and assign it the message after that we will redirect to index.php
at index.php we will check if $_SSESSION[‘msg’] is set if so we will display it as message and unset it.

see above code with sessions

At top on index.php page right after body tag

it can be improved more by creating a global custom functions for it
we can create single function but here I will make it simpler and do with two functions

  1. set_msg() Will set the message, it has 2 parameters 1st is mandatory which is message string, second one is optional which is message type to show message in green, yellow or red
  2. get_msg() it has no parameter, it checks id message is set it displays and unset it, this way on page refresh as it is unset so it will not be displayed again.

now let see above add.php and index.php code with these functions

At top on index.php page right after body tag

you can improve it more, here for learning purpose I kept it more simpler for beginners to learn easily. try it and comment your reviews, I will try my best to help you more.

your messages will display as below

Your account has been created successfully.

Warning Please fill in all required fields.

ERROR couldn’t create account, Please try later.


    Write a Reply or Comment

    Your email address will not be published. Required fields are marked *