Codeigniter doesn't save sessions in database - codeigniter

In config.php
$config['sess_driver'] = 'database';
$config['sess_save_path'] = 'ci_sessions';
$config['sess_cookie_name'] = 'cookiename';
$config['sess_expiration'] = 7200;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
//$config['sess_driver'] = 'files';
//$config['sess_save_path'] = BASEPATH . 'cache/sessions/';
Table:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` VARCHAR(128) NOT NULL,
`ip_address` VARCHAR(45) NOT NULL,
`timestamp` INT(10) UNSIGNED DEFAULT 0 NOT NULL,
`data` BLOB NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
That doesn't save the session in the database and the API doesn't return any response. If I change it to files it works fine.
[update]
Now I get this error:
Exception: Configured database connection is persistent. Aborting. /var/app/current/system/
libraries/Session/drivers/Session_database_driver.php 94

Take in consideration your dbprefix config.
If it's 'isci_', then your sessions table should be named 'isci_sessions' and sess_save_path the same.
Also you should change your database pconnect config to FALSE to fix the last issue.

Related

Codeigniter session was not stored in database when using database driver

Codeigniter session was not stored in database when using database driver on live server. But it's working fine local enviroment.
Codeigniter Version : 3.1.9
PHP Version : 7.2.11
Below my codeigniter configuration,
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 600;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 180;
$config['sess_regenerate_destroy'] = FALSE;
Anyone have idea, please advise.
First of all you got to change the configs to use database like this:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Then you have to create a table for your sessions and i've create a migration file for this:
class Migration_Create_ci_sessions extends CI_Migration
{
private $table;
public function __construct()
{
parent::__construct();
$this->load->dbforge();
$this->table = 'ci_sessions';
}
public function up()
{
$this->dbforge->drop_table($this->table, TRUE);
$ci_sessions = '`id` VARCHAR(128) NOT NULL,
`ip_address` VARCHAR(45) NOT NULL,
`timestamp` int(10) UNSIGNED DEFAULT 0 NOT NULL,
`data` BLOB NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)';
$this->dbforge->add_field($ci_sessions);
unset($ci_sessions);
$this->dbforge->create_table($this->table, TRUE);
}
public function down()
{
$this->dbforge->drop_table($this->table, TRUE);
}
}
or if you prefer you can use sql directly:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(128) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
and of course you have to load or autoload your database:
$autoload['libraries'] = array('database', 'session');
and set the configs for database correctly:
'username' => 'username',
'password' => 'password',
'database' => 'database',

chrome codeigniter redis clearing session issue

I am using the following settings for sessions in codeigniter.
$config['sess_driver'] = 'redis';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 0;
$config['sess_save_path'] = 'tcp://localhost:6379';//BASEPATH . 'cache/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
I am unable to logout and clear session on chrome (working fine on FF and safari ) by using the following
$this->session->sess_destroy();
$this -> session -> set_userdata('customer_login', false );
I had the same issue and was able to fix it with this
$this->load->driver('cache');
$this->session->sess_destroy();
$this->cache->clean();
ob_clean();
redirect('controller/method'); # or route
In your case
I don't think setting $this->session->set_userdata('customer_login', false ); is good way to check user logged.
When ever user logged use 'logged_in' => TRUE in session array and in method you can check if($this->session->userdata('item') == true )

How to set session in two different browser in same method with codeigniter?

I have same method to save session with codeigniter. It's work in chrome but in firefox can't save session.
You can go through below solutions and use depends on your needs.
if you are using filebase.
$config['sess_save_path'] = FCPATH . 'application/ci_sessions/';
If you store in database Then
$config['sess_driver'] = 'database'; // Change files to database
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions'; // This will be your database table for sessions
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
ci_session Table defination
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
Please note: If you are sharing same session with multiple domain than better to go with database storage.

ERR_RESPONSE_HEADERS_TOO_BIG error in chrome . How to solve it? [duplicate]

My web application develop using CodeIgniter 1.7 is having error ERR_RESPONSE_HEADERS_TOO_BIG when open with Chrome browser only. I tried with all other browser the error will not happen.
I can open the page normally after i refresh the error page. I try search from Google, it seems this bug happen to Chrome user since 2009 until now.
This is my controller code:
function search_daily_sales_summary_view()
{
if(!($this->session->userdata('DAILY_SALES_SUMMARY'))){
$this->session->set_flashdata('error', 'You dont have the permission to access that page.');
redirect('login/home');
}
$this->load->model('currency_model');
$this->load->model('bill_model');
$data = array();
$report = array();
if($query = $this->currency_model->list_currency())
{
foreach ($query as $row) {
$currencyid = $row->CURRENCY_ID;
$currencycode = $row->CURRENCY_CODE;
if($buyData = $this->bill_model->calculate_buy($currencyid))
{
$totalbuy = $buyData->total_from_amount;
$totalbuy_rate = $buyData->rate;
if($buyData->total_from_amount=='')
{
$totalbuy = 0.00;
}
if($buyData->rate=='')
{
$totalbuy_rate = 0.00;
}
}
else
{
$totalbuy = 0.00;
$totalbuy_rate = 0.00;
}
if($sellData = $this->bill_model->calculate_sell($currencyid))
{
$totalsell = $sellData->total_from_amount;
$totalsell_rate = $sellData->rate;
if($sellData->total_from_amount=='')
{
$totalsell = 0.00;
}
if($sellData->rate=='')
{
$totalsell_rate = 0.00;
}
}
else
{
$totalsell = 0.00;
$totalsell_rate = 0.00;
}
$report[] = array("currency"=>$currencycode, "buy"=>$totalbuy, "buyrate"=>$totalbuy_rate, "sell"=>$totalsell, "sellrate"=>$totalsell_rate);
}
$data['records'] = $report;
}
$this->load->model('company_model');
if($query = $this->company_model->list_company())
{
$data['company_list'] = $query;
}
$this->load->model('branch_model');
if($this->input->post('company'))
{
$companyid = $this->input->post('company');
if($query = $this->branch_model->view_company_branch($companyid))
{
$data['branch_list'] = $query;
}
}
else
{
if($query = $this->branch_model->list_branch())
{
$data['branch_list'] = $query;
}
}
$this->load->view('report/daily_sales_summary', $data);
}
How to solve this?
CI stores sessions in a cookie. If you store too much in a cookie, you get errors.
Set CodeIgniter to use DB sessions instead, or save this to a file.
Saving Session Data to a 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`)
);
Note: By default the table is called ci_sessions, but you can name it
anything you want as long as you update the
application/config/config.php file so that it contains the name you
have chosen. Once you have created your database table you can enable
the database option in your config.php file as follows:
$config['sess_use_database'] = TRUE;
Once enabled, the Session class will store session data in the DB.
Make sure you've specified the table name in your config file as well:
$config['sess_table_name'] = 'ci_sessions';
Note: The Session class has built-in garbage collection which clears out expired sessions so you do not need to write your own routine to do it.

CI_SESSION unknown table in 'order clause'

I use database table to store the ci_session. Here is my controller:
public function displayAllArticles()
{
// custom limit, set in zconfig for all tables
$customLimit = $this->config->item('articles_per_page');
// get the total number or records
$totalARTresults = $this->db->get('article')->num_rows();
// set the paging variables
if ($this->uri->segment(4) !="")
{
$limit = $this->uri->segment(4);
} else {
$limit = $customLimit;
}
$offset = 5;
$offset = $this->uri->segment(5);
$this->db->limit($limit, $offset);
// line bellow is the offending line <<<<<<<<<<<<<<<<<<<<<<<<
$this->db->order_by('articlecategoryID desc, articleSorder asc');
$data['articles'] = $this->articlesModel->get_with_category();
// session variables bellow are used in the view, for the
// code that display the message: Displaying x to y from total of z records
$this->session->set_userdata('totalARTresults', $totalARTresults);
$this->session->set_userdata('limit', $limit);
$this->session->set_userdata('offset', $offset);
$data['articles'] = array_splice($data['articles'], $offset, $limit);
// paging configuration
$this->load->library('pagination');
$config['base_url'] = site_url('/backEnd/articles/displayAllArticles/'.$limit.'/');
$config['total_rows'] = $totalARTresults;
$config['per_page'] = $limit;
$config['uri_segment'] = 5;
$config['full_tag_open'] = '<div class="dataTables_paginate paging_bootstrap pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li><a href=# style="color:#ffffff; background-color:#258BB5;">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
// initialize the paging
$this->pagination->initialize($config);
// create & load the variables needed for the view
$errorMessage = '';
$data['main_content'] = 'articles/articles';
$data['title'] = 'Articles';
$this->load->vars($data,$errorMessage);
$this->load->vars($this->currentUser);
$this->load->view('backOffice/template');
} // end of function displayAllArticles
When i call this function, i get the error message:
Error Number: 1054
Unknown column 'article.articlecategoryID' in 'order clause'
UPDATE ci_sessions SET last_activity = 1398256604, `...........
I have searched this site, and I found this:
CI_session and Error Number: 1054 (Unknown column ...)
but the solution: $this->db->_reset_write();
doesn't work.
Author there says that:
$this->session->userdata();
$this->session->set_userdata();
etc...
MUST BE used before/after execute your own CRUD ($this->db->...), but where ever i move the code for the session, i get same error.
Anyone can give me a hand with this? I know that I can just remove the order_by clausule in my controller, but I have plenty of legacy code that will have to be changed if I do so.
Any help will be deeply appreciated.
Regards, John
Make sure following things -
1) Order of auto-loading libraries (config/autoload.php)
$autoload['libraries'] = array('database','upload','session','form_validation');
// session loaded after database library
2) Having a ci_sessions table
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`)
);
//Refer: http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
// ensure table name: ci_sessions
3) Enable use of ci_sessions table in config/config.php
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 0;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions'; // ensure table name: ci_sessions
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 86400 * 30; //30 days

Resources