首页 > 解决方案 > PHP Codeigniter 3.1.10:无法更新会话数据

问题描述

碰巧卡住了将近一天。在谷歌搜索中搜索为什么这不能按预期工作,以及在 stackoverflow 中回答了几个问题,但无法弄清楚为什么它不能正常工作。基本上我在登录期间设置会话数据,比如

            foreach($response as $item) {
                $sess_array = array(
                    'user_id' => $item->id,
                    'photo' => $item->user_pic,
                );
            }
            // Create session
            $this->session->set_userdata('logged_in', $sess_array);

现在我正在尝试更新一个名为“照片”的特定变量。

$this->session->set_userdata('photo', $new_name);

当我尝试在我的视图中显示会话变量“照片”的值时,它仍然显示旧值而不是更新值。

以下是来自 config.php 的条目

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = BASEPATH . 'cache/sessions/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;

Codeigniter 版本 3.1.10 操作系统 Windows 10

请帮忙。

标签: codeigniter

解决方案


首先,只需检查您的 autoload.php 是否加载了会话库。或者在您的控制器中加载会话库。$this->load->library('session');

foreach($response as $item) { // looping your obj $response
                    $sess_array = array( // set an array 
                        'user_id' => $item->id,
                        'photo' => $item->user_pic,
                    );
                }

print_r($sess_array); you will get the last element of you $response obj here. 
                // Create session
                $this->session->set_userdata('logged_in', $sess_array); // here you are setting the last obj of $response in you session logged_in

`$this->session->set_userdata('photo', $new_name);` // here you store an variable $new_name in session `photo`

设置会话后,从控制器当前功能重定向到新功能。例如。

class session extend CI_Controller{
function set_session(){
 $new_name = 'xyz';
 $this->session->set_userdata('photo', $new_name);
 return redirect('session/get_session');
}
function get_session(){
 $this->load->view('sample');
}

}

在你看来sample.php

<body><h1>
<?php 
echo $this->session->userdata('photo'); 
// here you got out put 'xyz'
?>
</h1></body>

希望你能找到你出错的问题。


推荐阅读