php - 从 $_SESSION 获取数据

标签 php session

我正在尝试创建简单的服务器端验证,这是我的方法

public function create() {
        $name = $_POST['name'];

        session_start();
        unset($_SESSION['errors']);

        $count = $this->model->checkIfUserExists($name);
        if($count > 0) {       
            $_SESSION['errors'] = array(
                'message'   => 'User Already Exists',
                'variables' => array(
                    'name'     => $_POST['name'],
                    'password' => $_POST['password'],
                ),
            );  

            header('location: ' . URL . 'user/registration');
            exit;
        }           

        $data = array();
        $data['name'] = $_POST['name'];
        $data['password'] = $_POST['password'];
        $this->model->create($data);            
        header('location: ' . URL);
    }

和下面来自 registration.php

的代码
<?php 

if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {

echo '<ul>';
foreach ($_SESSION['errors'] as $error) {
    echo '<li>' . $error['message'] . '</li>';
}
echo '</ul>';
unset($_SESSION['errors']);
}
?>

但是我有错误

Warning: Illegal string offset 'message' in C:\xampp\htdocs\test\views\user\registration.php on line 6
�

Notice: Undefined index: message in C:\xampp\htdocs\test\views\user\registration.php on line 6

如何解决?

最佳答案

通常,Warning: Illegal string offset ... 意味着您正在尝试将字符串作为数组访问

目前,您正在将 $_SESSION['errors'] 设置为具有两个元素的关联数组,messagevariables。我相信您要实现的是创建一个包含多个错误的数组,每个错误都有一个 messagevariables

这样设置应该可以:

...

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

if ($count > 0) {
    $_SESSION['errors'][] = array(
        'message' = > 'User Already Exists',
        'variables' = > array(
            'name' = > $_POST['name'],
            'password' = > $_POST['password'],
        ),
    );

    header('location: '.URL.'user/registration');
    exit;
}

...   

空方括号向数组添加一个新元素:

$myArray[] = $myNewElement;

这样您就可以轻松地添加其他错误到列表中:

$_SESSION['errors'][] = array(
    'message' = > 'Error two',
    'variables' = > array(...),
);
$_SESSION['errors'][] = array(
    'message' = > 'Error three',
    'variables' = > array(...),
);

关于php - 从 $_SESSION 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35209985/

相关文章:

java - 我什么时候应该关闭从 Tapestry 中的 HibernateSessionManager 获取的 session ?

php - 为什么我不能连续运行两个以上的 jQuery ajax 调用?

shell - 我如何检查 stdin 是否存在于 PHP ( php-cgi ) 中?

macos - 保存整个桌面状态?

php - 如果同名变量为空, session 值将被删除

jsf - jsf 注销后发生 session 启动事件?

php - MySQL帮助: Good practice for my SQL Query

php - 如何使用 PHP 检测 CP437

php - cake_session 1213 : Deadlock found when trying to get lock; try restarting transaction

hibernate - Open Session In View 如何与 jms 连接/ session 一起使用?