Set User Session Per user in Codeigniter - codeigniter

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

Related

PHP Codeigniter 3.1.10: Unable to update session data

Happen to be stuck since almost a day. Scoured in google searching as to why this isn't working as expected, and also couple of answered questions in stackoverflow, but couldn't figure out as to why it's not working.
Basically i am setting session data during login, like
foreach($response as $item) {
$sess_array = array(
'user_id' => $item->id,
'photo' => $item->user_pic,
);
}
// Create session
$this->session->set_userdata('logged_in', $sess_array);
And now I am attempting to update a particular variable named 'photo'.
$this->session->set_userdata('photo', $new_name);
And when I try to display the value of the session variable 'photo' in my view, it still shows the old value and not the updated value.
Below are the entries from config.php
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = BASEPATH . 'cache/sessions/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
Codeigniter version 3.1.10
OS Windows 10
Please help.
First of all just check in you autoload.php did you load the session library or not.
or else load session library in your controller. $this->load->library('session');
foreach($response as $item) { // looping your obj $response
$sess_array = array( // set an array
'user_id' => $item->id,
'photo' => $item->user_pic,
);
}
print_r($sess_array); you will get the last element of you $response obj here.
// Create session
$this->session->set_userdata('logged_in', $sess_array); // here you are setting the last obj of $response in you session logged_in
`$this->session->set_userdata('photo', $new_name);` // here you store an variable $new_name in session `photo`
redirect from your controller current function to new function after setting the session.
for example.
class session extend CI_Controller{
function set_session(){
$new_name = 'xyz';
$this->session->set_userdata('photo', $new_name);
return redirect('session/get_session');
}
function get_session(){
$this->load->view('sample');
}
}
In your view sample.php
<body><h1>
<?php
echo $this->session->userdata('photo');
// here you got out put 'xyz'
?>
</h1></body>
Hope you can find the issue where you go wrong.

Retrive some data store in session with codeigniter

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 !!
}

Only show user_id and username after log in in codeigniter

I have a login and registration system in codeignitor.
This is my controller -
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
//$data['username'] = $session_data['username'];
$data = array(
'user_id'=>$session_data['user_id'],
'username'=>$session_data['username'],
'firstname'=>$session_data['firstname'],
'lastname'=>$session_data['lastname']
);
$this->load->view('home_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this code only show me the user_id and username. but not showing the firstname and lastname. Please help me ...
Considering that you have set your session like this,
$data = array(
'user_id'=>id,
'username'=>"name",
'logged_in'=>1,
);
$this->session->set_userdata($data);
To access values from session,
$this->session->userdata("name of session variable");
In your case,
$this->session->userdata("user_id");// for user id
$this->session->userdata("user_name");// for user name
if($result) {
$sess_array = array();
foreach($result as $row) {
$sess_array = array(
'user_id' => $row->user_id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
In your above given code I can't find the firstname in session setting. But you are trying to get firstname then how will the code provide you the firstname.

Codeigniter Session only writes userdata when sess_use_database is FALSE

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

Codeigniter - Passing multiple parameters

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.

Categories

Resources