手动设置会话到期时间 - CodeIgniter

时间:2022-11-23 20:44:56

How can I set session expiration time dynamically in codeigniter?

如何在codeigniter中动态设置会话到期时间?

For example, if a user logs in and has the role of admin, the expiration time should be longer than if a user logs in who does not have an admin role.

例如,如果用户登录并具有admin角色,则到期时间应该比用户登录时没有管理员角色的时间长。

Thanks.

谢谢。

8 个解决方案

#1


14  

You can update your session expiration time by increasing this variable in config file:

您可以通过在配置文件中增加此变量来更新会话到期时间:

$config['sess_expiration'] = 'somevalue'.

Set $config['sess_expiration'] = 0, if you want it to never expire.

设置$ config ['sess_expiration'] = 0,如果你想让它永不过期。

Here's a good discussion on CI forums:

这是关于CI论坛的一个很好的讨论:

Dynamically set configuration on session expire doesn’t work

在会话过期时动态设置配置不起作用

#2


9  

$data = array(
'username' => $this->input->post('username'),
'ADMIN_is_logged_in' => true
);

$this->session->sess_expiration = '14400';// expires in 4 hours
$this->session->set_userdata($data);// set session

#3


2  

None of these solutions address doing this dynamically or require another variable to be added to the session. The solution I came up with for CI 3.0.4 is to extend Session.php.

这些解决方案都没有动态地解决这个问题,或者需要将另一个变量添加到会话中。我为CI 3.0.4提出的解决方案是扩展Session.php。

  1. Create file application/libraries/Session/MY_Session.php

    创建文件application / libraries / Session / MY_Session.php

  2. Put the following into the file and modify for your logic of setting the $expiration variable. In my case I am pulling the value from a database. NOTE: If you have different expiration values per user type; there is a chance they could get garbage collected and expire unexpectedly due to different expirations with the same session. In this case I do NOT recommend this approach.

    将以下内容放入文件中并修改设置$ expiration变量的逻辑。在我的情况下,我从数据库中提取值。注意:如果每个用户类型有不同的到期值;由于同一会话的不同到期,他们有可能收集垃圾并意外过期。在这种情况下,我不推荐这种方法。

    <?php
    class MY_Session extends CI_Session 
    {
        public function __construct(array $params = array())
        {
            parent::__construct($params);
        }
    
        /**
         * Configuration
         *
         * Handle input parameters and configuration defaults
         *
         * @param   array   &$params    Input parameters
         * @return  void
         */
        protected function _configure(&$params)
        {
            $CI =& get_instance();
            $phppos_session_expiration = NULL;
    
            $CI->db->from('app_config');
            $CI->db->where("key", "phppos_session_expiration");
            $row = $CI->db->get()->row_array();
            if (!empty($row))
            {
                if (is_numeric($row['value']))
                {
                    $phppos_session_expiration = (int)$row['value'];
                }
            }
    
            $expiration = $phppos_session_expiration !== NULL ? $phppos_session_expiration : config_item('sess_expiration');
    
            if (isset($params['cookie_lifetime']))
            {
                $params['cookie_lifetime'] = (int) $params['cookie_lifetime'];
            }
            else
            {
                $params['cookie_lifetime'] = ( ! isset($expiration) && config_item('sess_expire_on_close'))
                    ? 0 : (int) $expiration;
            }
    
            isset($params['cookie_name']) OR $params['cookie_name'] = config_item('sess_cookie_name');
            if (empty($params['cookie_name']))
            {
                $params['cookie_name'] = ini_get('session.name');
            }
            else
            {
                ini_set('session.name', $params['cookie_name']);
            }
    
            isset($params['cookie_path']) OR $params['cookie_path'] = config_item('cookie_path');
            isset($params['cookie_domain']) OR $params['cookie_domain'] = config_item('cookie_domain');
            isset($params['cookie_secure']) OR $params['cookie_secure'] = (bool) config_item('cookie_secure');
    
            session_set_cookie_params(
                $params['cookie_lifetime'],
                $params['cookie_path'],
                $params['cookie_domain'],
                $params['cookie_secure'],
                TRUE // HttpOnly; Yes, this is intentional and not configurable for security reasons
            );
    
            if (empty($expiration))
            {
                $params['expiration'] = (int) ini_get('session.gc_maxlifetime');
            }
            else
            {
                $params['expiration'] = (int) $expiration;
                ini_set('session.gc_maxlifetime', $expiration);
            }
    
            $params['match_ip'] = (bool) (isset($params['match_ip']) ? $params['match_ip'] : config_item('sess_match_ip'));
    
            isset($params['save_path']) OR $params['save_path'] = config_item('sess_save_path');
    
            $this->_config = $params;
    
            // Security is king
            ini_set('session.use_trans_sid', 0);
            ini_set('session.use_strict_mode', 1);
            ini_set('session.use_cookies', 1);
            ini_set('session.use_only_cookies', 1);
            ini_set('session.hash_function', 1);
            ini_set('session.hash_bits_per_character', 4);
        }
    
    }
    

#4


0  

You can handle this with a custom controller. When a user logs in, set a session variable with the time of login. Create custom controller that contains a function in the constructor to check if the user is not admin user and if the timeout has expired. If it has, call $this->session->destroy(); Now, make all your controllers extend that controller instead of the CI base controller.

您可以使用自定义控制器处理此问题。用户登录时,使用登录时间设置会话变量。创建包含构造函数中的函数的自定义控制器,以检查用户是否不是admin用户以及超时是否已过期。如果有,请调用$ this-> session-> destroy();现在,让所有控制器扩展该控制器而不是CI基本控制器。

#5


-1  

use something like this:

使用这样的东西:

$user_type = $this->input->post('user_type');
if ($user_type == 'admin')
{
    //set session to non-expiring
    $this->session->sess_expiration = '32140800'; //~ one year
    $this->session->sess_expire_on_close = 'false';
}
else
{
    //set session expire time, after that user should login again
    $this->session->sess_expiration = '1800'; //30 Minutes
    $this->session->sess_expire_on_close = 'true';
}

//set session and go to Dashboard or Admin Page
$this->session->set_userdata(array(
    'id' => $result[0]['id'],
    'username' => $result[0]['username']
));

#6


-1  

At codeigniter go to applications/config.php and find the below configuration.

在codeigniter上转到applications / config.php并找到以下配置。

$config['sess_expiration'] = 14400; //in seconds

#7


-1  

In your login functionality just after user credentials have been verified you can check if user is admin and set different sessions accordingly. Something along these lines

在您的登录功能刚刚验证用户凭据后,您可以检查用户是否是管理员并相应地设置不同的会话。沿着这些方向的东西

<?php
/*
 *Assuming user is successfully veriefied and you've verified id user is admin*/

if($isAdmin==true){
$this->session->sess_expiration = 14400; // 4 Hours

}else{

// For ordinary users
$this->session->sess_expiration = 1800; // 30 minutes 
   

}
$this->session->sess_expire_on_close = FALSE;

#8


-3  

You can solve the session issue by replacing this:

您可以通过替换以下内容来解决会话问题:

$config['sess_use_database'] = TRUE;
$config['sess_encrypt_cookie'] = TRUE;

with this:

有了这个:

$config['sess_use_database'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;

#1


14  

You can update your session expiration time by increasing this variable in config file:

您可以通过在配置文件中增加此变量来更新会话到期时间:

$config['sess_expiration'] = 'somevalue'.

Set $config['sess_expiration'] = 0, if you want it to never expire.

设置$ config ['sess_expiration'] = 0,如果你想让它永不过期。

Here's a good discussion on CI forums:

这是关于CI论坛的一个很好的讨论:

Dynamically set configuration on session expire doesn’t work

在会话过期时动态设置配置不起作用

#2


9  

$data = array(
'username' => $this->input->post('username'),
'ADMIN_is_logged_in' => true
);

$this->session->sess_expiration = '14400';// expires in 4 hours
$this->session->set_userdata($data);// set session

#3


2  

None of these solutions address doing this dynamically or require another variable to be added to the session. The solution I came up with for CI 3.0.4 is to extend Session.php.

这些解决方案都没有动态地解决这个问题,或者需要将另一个变量添加到会话中。我为CI 3.0.4提出的解决方案是扩展Session.php。

  1. Create file application/libraries/Session/MY_Session.php

    创建文件application / libraries / Session / MY_Session.php

  2. Put the following into the file and modify for your logic of setting the $expiration variable. In my case I am pulling the value from a database. NOTE: If you have different expiration values per user type; there is a chance they could get garbage collected and expire unexpectedly due to different expirations with the same session. In this case I do NOT recommend this approach.

    将以下内容放入文件中并修改设置$ expiration变量的逻辑。在我的情况下,我从数据库中提取值。注意:如果每个用户类型有不同的到期值;由于同一会话的不同到期,他们有可能收集垃圾并意外过期。在这种情况下,我不推荐这种方法。

    <?php
    class MY_Session extends CI_Session 
    {
        public function __construct(array $params = array())
        {
            parent::__construct($params);
        }
    
        /**
         * Configuration
         *
         * Handle input parameters and configuration defaults
         *
         * @param   array   &$params    Input parameters
         * @return  void
         */
        protected function _configure(&$params)
        {
            $CI =& get_instance();
            $phppos_session_expiration = NULL;
    
            $CI->db->from('app_config');
            $CI->db->where("key", "phppos_session_expiration");
            $row = $CI->db->get()->row_array();
            if (!empty($row))
            {
                if (is_numeric($row['value']))
                {
                    $phppos_session_expiration = (int)$row['value'];
                }
            }
    
            $expiration = $phppos_session_expiration !== NULL ? $phppos_session_expiration : config_item('sess_expiration');
    
            if (isset($params['cookie_lifetime']))
            {
                $params['cookie_lifetime'] = (int) $params['cookie_lifetime'];
            }
            else
            {
                $params['cookie_lifetime'] = ( ! isset($expiration) && config_item('sess_expire_on_close'))
                    ? 0 : (int) $expiration;
            }
    
            isset($params['cookie_name']) OR $params['cookie_name'] = config_item('sess_cookie_name');
            if (empty($params['cookie_name']))
            {
                $params['cookie_name'] = ini_get('session.name');
            }
            else
            {
                ini_set('session.name', $params['cookie_name']);
            }
    
            isset($params['cookie_path']) OR $params['cookie_path'] = config_item('cookie_path');
            isset($params['cookie_domain']) OR $params['cookie_domain'] = config_item('cookie_domain');
            isset($params['cookie_secure']) OR $params['cookie_secure'] = (bool) config_item('cookie_secure');
    
            session_set_cookie_params(
                $params['cookie_lifetime'],
                $params['cookie_path'],
                $params['cookie_domain'],
                $params['cookie_secure'],
                TRUE // HttpOnly; Yes, this is intentional and not configurable for security reasons
            );
    
            if (empty($expiration))
            {
                $params['expiration'] = (int) ini_get('session.gc_maxlifetime');
            }
            else
            {
                $params['expiration'] = (int) $expiration;
                ini_set('session.gc_maxlifetime', $expiration);
            }
    
            $params['match_ip'] = (bool) (isset($params['match_ip']) ? $params['match_ip'] : config_item('sess_match_ip'));
    
            isset($params['save_path']) OR $params['save_path'] = config_item('sess_save_path');
    
            $this->_config = $params;
    
            // Security is king
            ini_set('session.use_trans_sid', 0);
            ini_set('session.use_strict_mode', 1);
            ini_set('session.use_cookies', 1);
            ini_set('session.use_only_cookies', 1);
            ini_set('session.hash_function', 1);
            ini_set('session.hash_bits_per_character', 4);
        }
    
    }
    

#4


0  

You can handle this with a custom controller. When a user logs in, set a session variable with the time of login. Create custom controller that contains a function in the constructor to check if the user is not admin user and if the timeout has expired. If it has, call $this->session->destroy(); Now, make all your controllers extend that controller instead of the CI base controller.

您可以使用自定义控制器处理此问题。用户登录时,使用登录时间设置会话变量。创建包含构造函数中的函数的自定义控制器,以检查用户是否不是admin用户以及超时是否已过期。如果有,请调用$ this-> session-> destroy();现在,让所有控制器扩展该控制器而不是CI基本控制器。

#5


-1  

use something like this:

使用这样的东西:

$user_type = $this->input->post('user_type');
if ($user_type == 'admin')
{
    //set session to non-expiring
    $this->session->sess_expiration = '32140800'; //~ one year
    $this->session->sess_expire_on_close = 'false';
}
else
{
    //set session expire time, after that user should login again
    $this->session->sess_expiration = '1800'; //30 Minutes
    $this->session->sess_expire_on_close = 'true';
}

//set session and go to Dashboard or Admin Page
$this->session->set_userdata(array(
    'id' => $result[0]['id'],
    'username' => $result[0]['username']
));

#6


-1  

At codeigniter go to applications/config.php and find the below configuration.

在codeigniter上转到applications / config.php并找到以下配置。

$config['sess_expiration'] = 14400; //in seconds

#7


-1  

In your login functionality just after user credentials have been verified you can check if user is admin and set different sessions accordingly. Something along these lines

在您的登录功能刚刚验证用户凭据后,您可以检查用户是否是管理员并相应地设置不同的会话。沿着这些方向的东西

<?php
/*
 *Assuming user is successfully veriefied and you've verified id user is admin*/

if($isAdmin==true){
$this->session->sess_expiration = 14400; // 4 Hours

}else{

// For ordinary users
$this->session->sess_expiration = 1800; // 30 minutes 
   

}
$this->session->sess_expire_on_close = FALSE;

#8


-3  

You can solve the session issue by replacing this:

您可以通过替换以下内容来解决会话问题:

$config['sess_use_database'] = TRUE;
$config['sess_encrypt_cookie'] = TRUE;

with this:

有了这个:

$config['sess_use_database'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;