PHP最佳方法:在重定向后显示通知

4
我需要在头部重定向页面后显示通知消息。我使用以下函数进行页面重定向:

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
这些被称为“Flash消息”,是的,你的方法是正确的。请参见http://mikeeverhart.net/php/session-based-flash-messages/。 - SirDarius
2个回答

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


0

是的,这是一个好方法。 你需要一些东西,可以通过请求保存数据。在php中,我们有cookie和session。对于这个来说,cookie不是一个好主意,而session则很好。 你可以为此创建一个类,并像这样显示通知:

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

例如,在Yii框架的用户模块中存在着与会话一起使用的"flashes"功能。

然后在显示时,从会话中删除该消息。 - Machiel
例如,他制作了这个。 - Andrey Vorobyev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接