Codeigniter session was not stored in database when using database driver - codeigniter

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',

Related

Codeigniter doesn't save sessions in database

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.

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.

session_id in codeigniter returns nothing

My CI_VERSION is 3.0.6.
now I want to echo session_id, but it returns nothing!
class MainIndex extends BaseController
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->library->load('session');
echo $this->session->userdata('session_id');
return ;
...
my config:
$config['sess_driver'] = 'files';
$config['sess_save_path'] = BASEPATH . 'soheil/files_cache/';
$config['sess_valid_drivers'] = array();
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 68400;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_session';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 68500;
Try to print all session data using.
Also make sure that you have loaded session in config/autoload.php
$autoload['libraries'] = array('session');
print_r($this->session->all_userdata());
also in order to use the session you are require to add some string in $config['encryption_key']
Just having a read in the Codeigniter user guide, it makes mention that session_id is no longer available via the sessions library since "sometime ago" (My Words, not theirs...)
The alternative they recommend is session_id().
Give that a shot!

Codeigniter session work fine on local but not working on Godaddy [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 6 years ago.
Improve this question
I developed website on php framework (Codeigniter) that working fine on my local (WAMP Server). When I upload it to Godaddy hosting, it unable to login into website. Below is the login class function.
public function index()
{
if ($this->session->userdata('admin_login') == 1)
redirect(base_url() . 'index.php?admin/dashboard', 'refresh');
$this->load->view('backend/login');
}
function ajax()
{
$response = array();
$email = $_POST["email"];
$password = $_POST["password"];
$response['submitted_data'] = $_POST;
$login_status = $this->validate_login( $email , sha1($password) );
$response['login_status'] = $login_status;
if ($login_status == 'success') {
$response['redirect_url'] = '';
}
echo json_encode($response);
}
function validate_login($email = '' , $password = '')
{
$credential = array( 'email' => $email , 'password' => $password );
$query = $this->db->get_where('users' , $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('admin_login', '1');
$this->session->set_userdata('admin_id', $row->id);
$this->session->set_userdata('name', $row->name);
$this->session->set_userdata('login_type', 'admin');
return 'success';
}
return 'invalid';
}
I realize that $this->session->set_userdata() method is not working on godaddy.
Please try this
Please add session library just like below.
$this->load->library('session');
if ($this->session->userdata('admin_login') == 1)
redirect(base_url() . 'index.php?admin/dashboard', 'refresh');
$this->load->view('backend/login');
First Load Session Library
then
Instead of Using this
if ($this->session->userdata('admin_login') == 1)
Use This
if ($this->session->userdata['admin_login'] == 1)
Check if it is working or not
Try a few alternatives may work:
Change these lines in application/config/config.php
$config['sess_cookie_name'] = 'cisession'; //remove(underscore)
$config['cookie_domain'] = ".example.com"; //make it site wide valid
You can store multiple session variable in array
function validate_login($email = '', $password = '') {
$credential = array('email' => $email, 'password' => $password);
$query = $this->db->get_where('users', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$sess_array = array(
'admin_login' => 1,
'admin_id' => $row->id,
'name', $row->name,
'login_type', 'admin'
);
$this->session->set_userdata('logged_in', $sess_array);
}
return 'invalid';
}
You need to upload session library in your constructor
public function __construct()
{
parent::__construct(); /* necessary! */
/* load model for calls to database */
$this->load->library('session');// load session library
$this->load->helper('url');
}
In your index you have to check user logged_in is set or not
public function index()
{
if ($this->session->userdata('logged_in')){// check session set or not
redirect(base_url() . 'index.php?admin/dashboard', 'refresh');
$this->load->view('backend/login');
}
}
OK, i assume you're using CI2, as you're getting FALSE on a non-existing session var. CI sessions use cookies and / or a database, depending on your config. what are the cookie settings on your config file?
you should pay attention to these settings:
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
and these ones (default config shown on both cases):
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$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;
is your site hosted on a subdomain? cookies are set via headers. is there any output being generated before your cookies are set? set up your log_threshold to 2 so you can see eventual errors and debug messages being generated.
$config['log_threshold'] = 2;
did you set up an encription key?
$config['encryption_key'] = '[there-must-be-something-here]';
I tried all answers that mention here, but not work for my issue.
My issue is
$this->session->userdata('admin_login') returns false.
Finaly I tried database to store session.
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
And created 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`)
);
Then it works fine
This should be Your Config Configuration
$config['sess_cookie_name'] = 'cisession';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$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'] = 300;
Also In your Model You must set the session.
public function login ()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user)) {
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'gender'=>$user->gender,
'user_num'=>$user->user_num,
'id' => $user->id,
'loggedin' => TRUE,
'balance' =>$user->balance,
'usertype' =>'admin',
);
$this->session->set_userdata($data);
}
}
this Works for me :)

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