php 如何在codeigniter中保存和提取会话数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17547489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:05:24  来源:igfitidea点击:

How to save and extract session data in codeigniter

phpcodeignitersession

提问by user2365514

I save some data in session on my verify controller then I extract this session data into user_activity model and insert session data into activity table. My problem is only username data saved in session and I can get and insert only username data after extracting session on model. I am new in Codeigniter. For this reason It's very difficult to find out the problem. I am trying several days finding the problem. But unfortunately I can't. So please, anyone help me. Thanks

我在验证控制器上的会话中保存了一些数据,然后将此会话数据提取到 user_activity 模型中,并将会话数据插入到活动表中。我的问题只是保存在会话中的用户名数据,在模型上提取会话后,我只能获取和插入用户名数据。我是 Codeigniter 的新手。因此,很难找出问题所在。我正在尝试几天发现问题。但不幸的是我不能。所以请任何人帮助我。谢谢

VerifyLogin controller:

验证登录控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
   $this->load->model('user_activity','',TRUE);
  }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }
 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');
   $vercode = $this->input->post('vercode');

   //query the database
   $result = $this->user->login($username, $password);

   // ip address
   $ip_address= $this->user_activity->get_client_ip();

   //Retrieving session data and other data
   $captcha_code=$_SESSION['captcha'];
   $user_agent=$_SERVER['HTTP_USER_AGENT'];

   if($result && $captcha_code == $vercode)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'username' => $row->username,
           'user_agent' => $row->user_agent,
           'ip_address' => $row->ip_address,
       );
       $this->session->set_userdata('logged_in', $sess_array);

        //insert user activity
       $this->user_activity->activity();
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>

user_activity model:

用户活动模型:

    <?php
    Class User_activity extends CI_Model
    {
     function activity()
     {
        if($this->session->userdata('logged_in'))
       {
         $session_data = $this->session->userdata('logged_in');
       //  $data['username'] = $session_data['username'];

           $data = array(
                  'session_id'=>"",
                  'ip_address'=>$session_data['ip_address'],
                  'user_agent'=>$session_data['user_agent'],
                  'username'=>$session_data['username'],
                  'time_stmp'=>Now(),
                  'user_data'=>$session_data['username']."Logged in Account"
                );
        $this->db->insert('user_activity',$data);        
       }
       else
       {
          return  false;
       }

       // Function to get the client ip address
    function get_client_ip() {
        $ipaddress = '';
        if ($_SERVER['HTTP_CLIENT_IP'])
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if($_SERVER['HTTP_X_FORWARDED_FOR'])
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if($_SERVER['HTTP_X_FORWARDED'])
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if($_SERVER['HTTP_FORWARDED_FOR'])
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if($_SERVER['HTTP_FORWARDED'])
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if($_SERVER['REMOTE_ADDR'])
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';

        return $ipaddress;
       }
      }
    }
    ?>

回答by MJVM

You can set data to session simply like this in Codeigniter:

您可以像这样在 Codeigniter 中将数据设置为会话:

$this->load->library('session');
$this->session->set_userdata(array(
    'user_id'  => $user->uid,
    'username' => $user->username,
    'groupid'  => $user->groupid,
    'date'     => $user->date_cr,
    'serial'   => $user->serial,
    'rec_id'   => $user->rec_id,
    'status'   => TRUE
));

and you can get it like this:

你可以像这样得到它:

$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');

回答by Mohammad Ismail Khan

First you have load session library.

首先你有加载会话库。

$this->load->library("session");

You can load it in auto load, which I think is better.

您可以在自动加载中加载它,我认为这更好。

To set session

设置会话

$this->session->set_userdata("SESSION_NAME","VALUE");

To extract Data

提取数据

$this->session->userdata("SESSION_NAME");

回答by Rajeev Ranjan

initialize the Session class in the constructor of controller using

使用以下命令在控制器的构造函数中初始化 Session 类

$this->load->library('session');

for example :

例如 :

 function __construct()
   {
    parent::__construct();
    $this->load->model('user','',TRUE);
    $this->load->model('user_activity','',TRUE);
    $this->load->library('session');
   }

回答by Prabin Tp

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

在 codeigniter 中,我们能够将会话值存储在数据库中。在 config.php 文件中创建 sess_use_database 变量true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

并在数据库中创建一个 ci_session 表

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

For more details and reference, click here

有关更多详细信息和参考,请单击此处

回答by Manish

CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.

CI Session Class 跟踪每个用户浏览站点时的信息。Ci Session 类生成自己的会话数据,为开发人员提供更大的灵活性。

Initializing a Session

初始化会话

To initialize the Session class manually in our controller constructor use following code.

要在我们的控制器构造函数中手动初始化 Session 类,请使用以下代码。

Adding Custom Session Data

添加自定义会话数据

We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.

我们可以在会话数组中添加我们的自定义数据。要将我们的数据添加到会话数组中,需要将包含新数据的数组传递给此函数。

$this->session->set_userdata($newarray);

Where $newarray is an associative array containing our new data.

$newarray 是一个包含我们新数据的关联数组。

$newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray); 

Retrieving Session

检索会话

$session_id = $this->session->userdata('session_id');

$session_id = $this->session->userdata('session_id');

Above function returns FALSE (boolean) if the session array does not exist.

如果会话数组不存在,则上述函数返回 FALSE(布尔值)。

Retrieving All Session Data

检索所有会话数据

$this->session->all_userdata()

$this->session->all_userdata()

I have taken reference from http://www.tutsway.com/codeigniter-session.php.

我参考了http://www.tutsway.com/codeigniter-session.php

回答by Chetan Panchal

In CodeIgniter you can store your session value as single or also in array format as below:

在 CodeIgniter 中,您可以将会话值存储为单个或数组格式,如下所示:

If you want store any user's data in session like userId, userName, userContact etc, then you should store in array:

如果你想在 session 中存储任何用户的数据,比如 userId、userName、userContact 等,那么你应该存储在数组中:

<?php
$this->load->library('session');
$this->session->set_userdata(array(
'userId'  => $user->userId,
'userName' => $user->userName,
'userContact '  => $user->userContact 
)); 
?>

Get in details with Example Demo :

使用示例演示获取详细信息:

http://devgambit.com/how-to-store-and-get-session-value-in-codeigniter/

http://devgabit.com/how-to-store-and-get-session-value-in-codeigniter/