Sending UI Messages in PHP
I am using sessions to save UI messages that can be shown to the user after an action has been formed (ie: logging in).
My initial problem was that the message persisted, while attempts to unset the session message didn’t allow for any messages to be shown.
Here’s how I solved the problem:
|
1 2 3 4 5 6 7 8 |
class Application { ... public function getMessages() { $messages = $_SESSION['messages']; unset($_SESSION['messages']); return $messages; } } |
First save the messages from the session, then you can delete them out of the session so they don’t persist past the one request.
Here is how I set the proper success or error message in the login function:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public function doLogin($username, $password) { ... if ( $username == $user->username && $password == $user->password ) { $_SESSION['logged_in'] = true; $this->addMessage('You are now logged in.', 'success'); } else { $_SESSION['logged_in'] = false; $this->addMessage('We were unable to log you in.', 'error'); } return $this->isLoggedIn(); } |