【问题标题】:Codeigniter Session databaseCodeigniter 会话数据库
【发布时间】:2011-01-05 00:37:50
【问题描述】:
我正在尝试构建一个系统来记住用户与网站的交互,例如我的网站允许用户构建自己的导航系统,但我希望系统能够记住他们选择的导航系统,而无需用户必须注册,我假设我需要为这些使用会话/cookie,并且我进一步假设我需要使用 cookie,因为它们在浏览器关闭时不会过期(我知道它们会在一段时间后过期) .
所以我已经使用 codeigniter 会话库进行设置,并将会话 ID 保存到数据库中。我需要知道的是如何使用会话和 cookie 保存用户导航选择,例如,如果用户选择使用博客导航,那么我需要能够保存它,以便下次他们访问该站点时,博客导航是用过的。有人可以指出我正确的方向吗?请不要指向我的手册。我已经尝试过 cookie 助手,无论我尝试什么,cookie 都不会设置。
【问题讨论】:
标签:
php
codeigniter
session
cookies
【解决方案1】:
当客户选择导航系统时,您需要将客户的导航选择保存在数据库中。
使用登录。
从数据库中拉取数据。
我在控制器中提取这样的客户信息。
...
if(isset($_SESSION['customer_id'])){
$data['fname'] = $_SESSION['customer_first_name'];
$data['lname'] = $_SESSION['customer_last_name'];
$data['telephone'] = $_SESSION['phone_number'];
$data['email'] = $_SESSION['email'];
$data['address'] = $_SESSION['address'];
$data['city'] = $_SESSION['city'];
$data['pcode'] = $_SESSION['post_code'];
}
$this->load->vars($data);
$this->load->view('welcome/template');
这是我的登录控制器/登录
function login(){
// $data['loggedin']=0;
if ($this->input->post('email')){
$e = $this->input->post('email');
$pw = $this->input->post('password');
$this->MCustomers->verifyCustomer($e,$pw);
if (isset($_SESSION['customer_id'])){
// $data['loggedin']=$_SESSION['customer_id'];
$this->session->set_flashdata('msg', 'You are logged in!');
redirect('welcome/login','refresh');
}
$this->session->set_flashdata('msg', 'Sorry, your email or password is incorrect!');
redirect('welcome/login','refresh');
}
$data['main'] = 'welcome/customerlogin';// this is using views/login.php
$data['title'] = "Customer Login";
$this->load->vars($data);
$this->load->view('welcome/template');
}
然后退出
function logout(){
// or this would remove all the variable in the session
session_unset();
//destroy the session
session_destroy();
redirect('welcome/index','refresh');
}
【解决方案2】:
我知道您要求不要指向手册,但它确实会给您答案。您不需要直接与 cookie 交互来做您想做的事情,sessions 为您处理。只要您不保存任何敏感数据,您就可以将会话设置保留为默认设置,这会将会话数据保存到用户计算机上的 cookie 中,但您需要进行一些小调整以确保延长超时时间。
首先,请阅读:Session Class : CodeIgniter User Guide
然后就可以加载会话库了:
$this->load->library("session");
并将数据保存到会话中:
$this->session->set_userdata("navigation_choice_a", "navigation_value_a");
然后稍后使用:
$this->session->userdata("navigation_choice_a");
// Will return "navigation_value_a"
您还可以将数字、类和数组保存到会话中,它们将在读取数据时再次重构。
最后一件事,为了确保会话不会在两小时后过期,在您的配置中,将带有 $config['sess_expiration'] 的行更改为:
$config['sess_expiration'] = 0;
这将确保会话不会过期。
【解决方案3】:
清除我们使用的会话:
$this->session->unset_userdata('navigation_choice_a');