PHP从session取数据乱码PHP–从$_SESSION获取数据怎么解决? 我正在尝试创建简单的服务器端验证,这是我的方法 publicfunctioncreate(){$name=$_POST[name];session_start();unset($_SESSION[errors]);$count=$this-mod
我正在尝试创建简单的服务器端验证,这是我的方法
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的代码
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) { echo ' '; foreach ($_SESSION['errors'] as $error) { echo ' ' . $error['message'] . ''; } echo ' '; 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解决方法:通常,警告:非法字符串偏移…表示您尝试以字符串形式访问字符串.
目前,您将$_SESSION[‘errors’]设置为具有两个元素(消息和变量)的关联数组.我相信你想要实现的是创建一个包含多个错误的数组,每个错误都有一个消息和变量.
像这样设置应该做:
$_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(...), );