从$ _SESSION获取数据

时间:2016-02-04 19:34:32

标签: 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

如何解决?

3 个答案:

答案 0 :(得分:5)

通常,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(...),
);

答案 1 :(得分:0)

这是因为foreach遍历主阵列中的项目。 [&#34;消息&#34;,&#34;变量&#34;]

像这样分配$_SESSION['errors'] =$_SESSION['errors'][] =

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

答案 2 :(得分:0)

第一次开始会话session_start()

registration.php

<?php 
session_start();
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']);
}
?>