php重定向后显示通知的最佳方式

时间:2014-12-12 13:50:40

标签: php session

我需要在标题重定向页面后显示通知消息。我使用此功能重定向页面:

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;
}
   }

我在php SESSION中插入错误,如下所示:

session_start();
$_SESSION['errors'] = array();

...

array_push($_SESSION['errors'], "<span style = 'color:green;'>Success!</span>");
Redirect("somepage.php"); // OR header("Location: somepage.php");

显示通知:

if(isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
    foreach($_SESSION['errors'] as $k => $v)
        echo($v . "<br/>");
    unset($_SESSION['errors']);
}

SESSION中发出通知是否安全且好的方式?如果没有,在标题重定向后显示通知的最佳方法是什么?!

2 个答案:

答案 0 :(得分:1)

我为这类项目编写了一个库https://github.com/tamtamchik/simple-flash

安装完成后,您可以这样做:

// put message not session
flash('Some error message', 'error');

// print it after redirect
echo flash()->display(); 

它会生成Bootstrap个友好的警报消息。

Example

答案 1 :(得分:0)

是的,这是好方法。 您需要的东西,可以通过请求保存数据。在PHP中我们有cookie和会话。 Cookie这是个糟糕的主意,会话很好。 您可以为此制作课程,并显示如下通知:

if ($oNotification->hasNotification('key'))
{
$oNotification->showNotification('key');
}

例如,在Yii Framework中,用户模块中存在“闪烁”,与会话

一起使用