CodeIgniter Session Expire in Config file - codeigniter

I am working on CodeIgniter framework.
What I want, is to set the session expiring time of the site to 3 hours ie, (3600*3=10800 seconds).
But when I set the $config['sess_expiration'] = 10800; in config.php, the session is getting expired within around 30 minutes of idle and is redirected to login page.
Why is this happening?
These are some of my session settings in config
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 10800;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;

Make sure you have the ci_sessions table in your database.
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) 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`)
);
EDIT: also, make sure you are not using $_SESSION versus $this->session->set_userdata($array);
Link: http://codeigniter.com/user_guide/libraries/sessions.html

Check the code like this:
if($login)
{
$this->session->sess_expire_on_close = TRUE;
}
else
{
$this->session->sess_expiration = 60*60*3;
$this->session->sess_expire_on_close = FALSE;
}
$this->session->set_userdata('your_item');

Check your configuration of session.gc_lifetime in php.ini.
By default, this is 1440, or 24 minutes. This means that whenever PHP's garbage-collector runs (it does this with a configured probability on every pageload), any sessions older than 24 minutes will be cleared out via the gc() function in your CodeIgniter session driver.

Related

codeigniter A Database Error Occurred

Can someone help me?
I am a beginner and trying to make wearing CodeIgniter authentication, but when I try to make an error like this
A Database Error Occurred
Error Number: 1046
No database selected
SELECT * FROM (`user`) WHERE `user_username` = 'amanda' AND user_passwordMD5("12345") =
Filename: C:\xampp\htdocs\codeigniter\system\database\DB_driver.php
Line Number: 330
thanx
please make sure you have setup database configuration in application/config/database.php file
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'my_database';
Check the database.php file in application/config/
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'mypassword';
$db['default']['database'] = 'my_database'; // here is the database selection
Open the file application/config/database.php file and change the following line:
$db['default']['dbdriver'] = 'mysql';
To:
$db['default']['dbdriver'] = 'mysqli';
This shift to mysqli saved by day.
Lost connection to MySQL server during query
Line Number: 337
people who critic here should have not only education but also common sense. they should know also what time I made this comment and what was my reputation score. It is not only about giving an answer but the giving also the suggestion a beginner can pin-point the problem. I could have given the answer but just after posting my comment someone already given answer. Look below - best among anyone given here
$config['hostname'] = "localhost";
$config['username'] = "username";
$config['password'] = "password";
$config['database'] = "database";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";

options array in Joomla session?

I've been analyzing joomla session and I came across a few problems. One of the problems is the session name.
See this code:(seesion.php#894)
protected function _setOptions(array $options)
{
// Set name
if (isset($options['name']))
{
session_name(md5($options['name']));
}
// Set id
if (isset($options['id']))
{
session_id($options['id']);
}
// Set expire time
if (isset($options['expire']))
{
$this->_expire = $options['expire'];
}
// Get security options
if (isset($options['security']))
{
$this->_security = explode(',', $options['security']);
}
if (isset($options['force_ssl']))
{
$this->_force_ssl = (bool) $options['force_ssl'];
}
// Sync the session maxlifetime
ini_set('session.gc_maxlifetime', $this->_expire);
return true;
}
My problem is with the $options array , I add this to the script:
print_r($options);
the result was: Array ( [name] => 266e79f0eac297f66eaf7926636f03fa [expire] => 900 )
where did this element come from ? I mean is there a value that will allow me to do this:
md5('value');
and get the same [name] element
Hey i found the answer for this.
The session value is calculated as following.
$hash = md5(md5($secret.'site'));
where $secret is defined in the configuration file.
use following code to get the session value.
include_once(dirname(dirname(FILE)).DIRECTORY_SEPARATOR.'configuration.php');
$config = new JConfig;
$secret = $config->secret;
$hash = md5(md5($secret.'site'));
So for you the value of name variable comes from md5($secret.'site') which is session value. and if you take md5 again it will give you the session cookie value.

Why the Codeigniter session does not expire after closing the browser?

Problem scenario
If a user A logs into the application then the user id set in session. After doing some tasks user A closes his browser and leaves the computer. Short time later, user B came and open browser and see the application was in logged in state. User B can also open an internal url, which directly redirects him into the application without any authentication by using the previous session.
My Configuration
$config['sess_cookie_name'] = 'cisession';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
You can override or Set a Config Item dynamically. If you simply look at $config['sess_expire_on_close'] = TRUE;
Whether to make the session to expire automatically when the browser window is closed.
Set it to true if user did not check the remember me checkbox. And the session will expire after user close the browser.
And if he checks the remember me checkbox, set $config['sess_expire_on_close'] to FALSE like
if($this->input->post('remember')) $this->config->set_item('sess_expire_on_close', '0'); //'remember' is checkbox name.
now session will not expire after browser is closed.
note: this solution is also tested on Opera, Mozilla, Chrome and ie9
Try this, may be it help you
/ **
* Escape String
*
* #param string
* #param bool whether or not the string will be used in a LIKE condition
* #return string
*/
public function escape_str($str, $like = FALSE)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = $this->escape_str($val, $like);
}
return $str;
}
$str = is_resource($this->conn_id) ? mysql_real_escape_string($str, $this->conn_id) : addslashes($str);
// escape LIKE condition wildcards
if ($like === TRUE)
{
return str_replace(array($this->_like_escape_chr, '%', '_'),
array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
$str);
}
return $str;
}
// --------------------------------------------------------------------
Set in application/config/config.php:
$config['sess_expiration'] = 0;
$config['sess_expire_on_close'] = TRUE;
This should be OK.
Why don't you use the CI session function to do that
http://www.codeigniter.com/userguide2/libraries/sessions.html

Codeigniter sessions issue

I am using codeigniter. I have a weird problem with the sessions. I set the session when the user logs in and redirects him to a new page. I observe that the sessions are set sometimes and sometimes they aren't set. I have tried using codeigniter sessions & native sessions with sess_use_database variable TRUE and FALSE. I have no idea of what's going on.
This is how the config file looks like:
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 7200;
When session data is available in a database, every time a valid session is found in the user's cookie, a database query is performed to match it. If the session ID does not match, the session is destroyed. Session IDs can never be updated, they can only be generated when a new session is created.
In order to store sessions, you must first create a database table for this purpose.
Create it in your DB:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) 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`)
);
When, go at config and and change:
$config['sess_use_database'] = TRUE;
I prefer to save the session in database because it is more secure and works without problem.
Where is your sess_cookie setting? I dont see it there?
$config['sess_cookie_name'] = 'cookiename';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 7200;
Make sure whatever cookie name you pick does NOT have an underscore. i.e:
$config['sess_cookie_name'] = 'mycookie'; // good
$config['sess_cookie_name'] = 'my_cookie'; // bad
Had the same issue and what I found it having
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
Will insert 2 records in the session table, the first record with the data and the second record with nothing hence the session data not accessible. When you change
$config['sess_encrypt_cookie'] = FALSE;
to false it will only insert one record into the session table with all the data and all will be right with the world :)
I think that it's just not getting updated as supposed and it creates a new one on every page request. (common Codeigniter's setting issue)
here's my suggestions:
double check your Application/Config/config.php file to ensure that the part of session domain looks like that if you host the site on the main directory:
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "yourdomain.com";
$config['cookie_path'] = "var/sessions/";
$config['cookie_secure'] = FALSE;
and like that if you host the site on a sub-directory:
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "yourdomain.com";
$config['cookie_path'] = "siteSubDirectory/var/sessions/";
$config['cookie_secure'] = FALSE;
and also make sure that the 2 directories are writable by fixing their permissions to 755 or so, and I strongly recommend that you enable database session, it's more secure and will help you find out the real problem by checking the session table. good luck :)
try $config['sess_match_useragent'] = FALSE;
i'm experiencing the same issue with sessions and redirects and i've hacked my cms to find out what's causing this. setting that in config.php worked for me.

Set Session Expiration Time Manually-CodeIgniter

How can I set session expiration time dynamically in 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.
Thanks.
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.
Here's a good discussion on CI forums:
Dynamically set configuration on session expire doesn’t work
$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
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.
Create file application/libraries/Session/MY_Session.php
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.
<?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);
}
}
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.
In Codeigniter 4
Go to the file App=>Config=>App.php
Find the var $sessionExpiration
The default value for this var is 7200
Change it to the value as you want your session to be alive.
The complete config for the session is given below:
public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler';
public $sessionCookieName = 'ci_session';
public $sessionExpiration = 7200;
public $sessionSavePath = WRITEPATH . 'session';
public $sessionMatchIP = false;
public $sessionTimeToUpdate = 300;
public $sessionRegenerateDestroy = false;
Session will expire in 10 seconds
$config['sess_expiration']= 10;
Session will not expire
$config['sess_expiration']= 0;
In Codeigniter 4, I do it the other way.
Set the session expiration time to maximal value (for example month for everybody) then in your controller or libraries, if the user is not admin, check the last active time, if time is more than what you need, destroy session and require log in.
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']
));
At codeigniter go to applications/config.php and find the below configuration.
$config['sess_expiration'] = 14400; //in seconds
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;
I think the most better chooice is using session temp_data and always you can change is dynamically and it is not depended your 'sess_expiration' in config file:
$this->session->set_tempdata('admin_session', true, 72000);
$this->session->set_tempdata('user_session', true, 14400);
where you check admin or user login state, like 'ADMIN_is_logged_in?'
check the remained 'tempdata' lifetime by:
if($this->session->tempdata('admin_session')){
//do something }
else{
//session timeout and is time to destroy all sessions
session_destroy();
}
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;

Resources