I need to Display notification message after header redirect page. i redirect page using this function :
function Redirect($url) {
if(!headers_sent()) {
//If headers not sent yet... then do php redirect
header('Location: '.$url);
exit;
} else {
//If headers are sent... do javascript redirect... if javascript disabled, do html redirect.
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>';
exit;
}
}
I insert error in php SESSION
like this :
session_start();
$_SESSION['errors'] = array();
...
array_push($_SESSION['errors'], "<span style = 'color:green;'>Success!</span>");
Redirect("somepage.php"); // OR header("Location: somepage.php");
And for display notification:
if(isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
foreach($_SESSION['errors'] as $k => $v)
echo($v . "<br/>");
unset($_SESSION['errors']);
}
Put notification in SESSION
is safe and good way? if not, what's best way for show notification after header redirect ?!
Yes, it's good way. You need's something, that may save data through requests. In php we have cookie and session. Cookie it's bad idea for that, session good. You may make class for this, and show notifications like this:
if ($oNotification->hasNotification('key'))
{
$oNotification->showNotification('key');
}
For example, in Yii Framework in User Module exists "flashes" working with sessions
I wrote a library just for this type of projects https://github.com/tamtamchik/simple-flash.
Once you have it installed you can do this:
// put message not session
flash('Some error message', 'error');
// print it after redirect
echo flash()->display();
It'll generate Bootstrap friendly alert messages.