I'm new to codeigniter and so when I set up my log in code I started out with simple and kept updating it to be more complex/secure. With that said I was making great progress creating a session and adding a user_data variable called "login_status" set to "1". To use as a reference for future page requests. Eventually I decided to go ahead and set up the database table ci_sessions and switch to that instead of just using a cookie. When I did this, all of the sudden my "login_status" variable was not being written anymore. As a result I could no longer access any subsequent pages and kept being redirected back to the log in screen.
In short, this exact same code works perfectly when I have sess_use_database set to false.
I'm not sure why this is happening but any help would be greatly appreciated!
Log in Controller:
class login extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('form');
}
public function index($login = "")
{
$data = array();
if ($login == "failed")
$data['loginFailed'] = true;
else
$data['loginFailed'] = false;
$this->load->view('templates/headerAdmin');
$this->load->view('admin/loginform', $data);
$this->load->view('templates/footerAdmin');
}
public function assessme()
{
$username = $_POST['username'];
$password = md5($_POST['password']);
//checkme works fine and returns true
if ($this->checkme($username, $password))
{
$newdata = array( 'login_status' => '1' );
$this->session->set_userdata($newdata);
$this->mainpage();
}
else {$this->index("failed");}
}
public function checkme($username = "", $password = "")
{
if ($username != "" && $password != "")
{
$this->load->model('admin/loginmodel');
if ($this->loginmodel->validateCredentials($username, $password))
return true;
else
return false;
}
else
{
return false;
}
}
public function mainpage()
{
redirect('admin/dashboard');
}
The controller that I am redirected to after I can successfully log in:
class dashboard extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index() {
//Make sure user is logged in
$login_status = $this->session->userdata('login_status');
//This is where I am redirected because the user_data is not being set
if(!isset($login_status) || $login_status != '1') {
redirect('admin/login');
}
$this->load->view('templates/headerAdmin');
$this->load->view('admin/dashboard/list');
$this->load->view('templates/footerAdmin');
}
}
Config:
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$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;
EDIT : Setting 'sess_match_useragent' to FALSE seems to prevent the session from being destroyed. Hopefully that will provide other clues as to what the cause of my problem is but obviously this, in itself, isn't an ideal solution
I had this problem and I fix it by this page
http://philsbury.co.uk/blog/code-igniter-sessions
This page say u should change Session library in \system\libraries
I Rename default Session file And create new Session file and put the code on it
its Worked
Related
I have my little project running perfectly on my local computer. However, when I run it into my laptop, an entry is automatically loaded in my ci_sessions table each time the page is being reloaded or refresh. I am using the database as my session driver.
Based on the screenshot: row 4 says that my login session store successfully. However, the 2 extra rows (5, 6) that are being added cause this code to fail:
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
here's my config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$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;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
Here's my Page Controller
<?php
class Pages extends MY_Controller
{
public function view($page = 'login')
{
if (!file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
if($page == 'login') {
$this->isLoggedIn();
$this->load->view($page, $data);
}
else{
$this->isNotLoggedIn();
$this->load->view($page, $data);
}
}
}
MY_Controller Class
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
public function isLoggedIn()
{
if($this->session->userdata('logged_in') === true) {
redirect('home', 'refresh');
}
}
public function isNotLoggedIn()
{
if($this->session->userdata('logged_in') !== true) {
redirect('login', 'refresh');
}
}
}
So far I have already tried adding the code below to my autoload.php but no luck.
$autoload['libraries'] = array('database', 'session');
Note: again this works in another unit with a similar setup.
after trying some work around, Codeigniter 3 is not yet compatible with php 7. I have to downgrade my php version to 5.6 to make it work. thanks folks for helping.
I suffered a lot of troubles with the original CI session library (included what you mention). Finally I arrived to this replacement that use native PHP session. It works!
Believe me, in the middle of a project, I did not stop to wonder why. Just works.
Here it is: CodeIgniter Native Session
BUT, due that it is an old library you MUST made some hacks. You can check those simple hacks in the library's forum
Just drop this file in codeigniter's library directory.
I need to store some data that i get via an ajax request on a method, and later retrive them when i call another method.
public function updateInt()
{ $this->load->library('session');
$interval = $this->input->post('_interval');
$aInt = array('my_interval' => $interval);
$this->session->set_userdata('post', $aInt);
$_interval_ = $this->session->userdata['post']['my_interval'];
return $_interval_;
}
public function getInt()
{
$interval = $this->updateInt();
// print $interval and do some stuff !!
}
// This return a null, but I need the value set on the front-end by the user and passed with an ajax call to updateInt() method.
I need some help because I'm newbie with codeignter.
Make sure you have set your sessions in your config.php do not leave the session save path null
Example
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = APPPATH . 'cache/session/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Make sure session folder permission 0700
Make sure you are getting correct post data what your after
public function updateInt()
{
// You can autoload it in config/autoload.php saves loading every page
$this->load->library('session');
$aInt = array('my_interval' => $this->input->post('_interval'));
$this->session->set_userdata('post', $aInt);
// Use `(` and `)` not `[]`
$interval = $this->session->userdata('post');
return $interval;
}
public function getInt()
{
$interval = $this->updateInt();
// Test
echo $interval['my_interval'];
// print $interval and do some stuff !!
}
In my default config.php, all user session will expired base on the value provided
$config['sess_expiration'] = 7200;
And I have a specific user that I need to set session expiration different from the others, lets say 15 minutes
This is what I tried
SomeController
function __construct()
{
parent::__construct();
$this->load->model('store_manager/Storemanager_model');
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data = array(
'username' => $session_data['username'],
);
$this->session->sess_expiration = '300';// expires in 15 minutes
$this->session->set_userdata($data);// set session
}
Does not work, returns blank page
Update
I modify this code adding some condition
function __construct()
{
parent::__construct();
$this->load->model('store_manager/Storemanager_model');
if($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$user = $session_data['username'];
if ($user == 'retailer_1')
{
//set session to non-expiring
$this->session->sess_expiration = '32140800'; //~ one year
// $this->session->sess_expire_on_close = 'false';
}
}
}
Still getting blank page
I am trying to pass multiple parameters to my model from my controller. It seems that the $scholId that I am trying to pass won't go through to the model after I submit the form. However, the $userId goes through to the database just fine. Is there something wrong with $this->uri->segment(4) that won't pass through correctly?
function apply()
{
$this->load->helper('form');
$this->load->library('form_validation');
$scholId = $this->uri->segment(4);
$userId = '2'; //User query -> this will be taken from session
$this->data['scholarship'] = $this->scholarship_model->getScholarship($scholId);
$this->data['title'] = "Apply";
$this->form_validation->set_rules('essay', 'Essay', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $this->data);
$this->load->view('student/page_head', $this->data);
$this->load->view('student/form', $this->data);
$this->load->view('templates/footer', $this->data);
}else{
// Validation passes
$this->users_model->applySchol($userId,$scholId);
redirect('/scholarships');
}
}
you need to check up the segment whether it exists or not before passing it Like:
if ($this->uri->segment(4) === FALSE)
{
$schoId = 0; //or anything else so that you know that does not exists
}
else
{
$schoID= $this->uri->segment(4);
}
or simply:
$product_id = $this->uri->segment(4, 0);
//which will return 0 if it doesn't exists.
This is sample of function in the Staff controller for this question
function newStaff()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
From the function add_newStaff(), i need to load back all the data from database if the form validation return false. This can be troublesome since I need to maintain two copy of codes. Any tips that I can use to prevent this?
Thanks.
Whats preventing you from doing the following
function newStaff()
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
private function _getData()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
return $data;
}
Alternately you change the action your form submits to so that it points to the same service you use for the initial form request with something like the following. This would also mean that you'd have the POST values retained between page-loads if you wanted to retain any of the submitted values in your form.
function newStaff()
{
// validation rules
if ($this->validation->run() == TRUE)
{
//submit data into DB
}
else
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
}