【发布时间】:2016-02-27 07:06:49
【问题描述】:
所以我创建了一个注册页面,并且我也在使用会话来显示消息。 该会话称为“flash”,我为会话创建了一个抽象类以使其更容易。
这是我的 Session 课程:
public static function exists($name)
{
return (isset($_SESSION[$name]) ? (true) : (false));
}
public static function set($name, $value)
{
return $_SESSION[$name] = $value;
}
public static function delete($name)
{
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function get($name)
{
if(self::exists($name)) {
return $_SESSION[$name];
}
return '';
}
public static function hasFlash()
{
return (Session::exists('flash') ? (true) : (false));
}
public static function addFlash($message)
{
if(Session::exists('flash'))
{
$msgArray = (Array) Session::get('flash');
array_push($msgArray, $message);
Session::set('flash', (Array) $msgArray);
}
else
{
$msgArray = array();
array_push($msgArray, $message);
Session::set('flash', (Array) $msgArray);
}
}
public static function flash($message = null)
{
if(self::hasFlash()) {
$msgArray = (Array) Session::get('flash');
Session::delete('flash');
foreach($msgArray as $message) {
echo $message . "<br>";
}
}
return '';
}
这是我的注册页面:
$hasError = false;
$username = Functions::escape(Input::get('user'));
$password = Functions::escape(Input::get('password'));
$email = Functions::escape(Input::get('email'));
$nick = Functions::escape(Input::get('nick'));
if(User::userExists($username, $db)) {
Session::addFlash("User $username is taken, try another one.");
$hasError = true;
}
if(User::emailExists($email, $db)) {
Session::addFlash("Email $email is taken, try another one.");
$hasError = true;
}
if(!$hasError)
{
User::addUser($username, $email, $password, $nick, $db);
Session::addFlash("You have successfully registered.");
Session::addFlash("You can now login with $username.");
Functions::location("index.php");
}
这是我用来显示 Flash 消息的代码:
<?php if(Session::hasFlash()) : ?>
<div class="form-group">
<?php Session::flash(); ?>
</div>
<?php endif; ?>
但是它仅在注册页面上有效,例如当用户输入用户名/电子邮件时,上面的代码将显示消息,尽管当我注册用户并将他发送到索引页面时,2 成功消息不会显示。我确实在页面顶部有 session_start。
【问题讨论】:
-
你试过省略 return "";从 Flash 功能结束?
-
是的,它不起作用。虽然当我简单地设置 $_SESSION['msg'] = "test";它可以在任何页面上工作,但是由于某些奇怪的原因,该数组不会出现在任何页面上......