PHP Codeigniter 3.1.10: Unable to update session data - codeigniter

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.

Related

How to set_userdata after session_destroy in codeginiter?

For some reasons I need to destroy all sessions in a controller in my codeigniter and set new one immediately after that. but as you can see in the following example, seems it is not working in Codeigniter version 3.1.9 or my usage is in wrong way.
I have this controller in my Codeigniter:
<?php
class Test extends CI_Controller {
public function index()
{
$this->load->library('session');
$this->session->sess_destroy();
$session_data = array (
'key_1' => 'value_1',
'key_2' => 'value_2',
'key_3' => 3
);
$this->session->set_userdata($session_data);
$this->session->set_userdata('key_4', 4);
print_r($_SESSION);
}
public function next()
{
$this->load->library('session');
print_r($this->session->all_userdata());
}
}
When I open MYDOMAIN.COM/test, the output is like this:
Array ( [__ci_last_regenerate] => 1545508348 [key_1] => value_1 [key_2] => value_2 [key_3] => 3 [key_4] => 4 )
but immediately after that, if I open MYDOMAIN.COM/test/next, the output is empty like this:
Array ( [__ci_last_regenerate] => 1545509049 )
In the config.php the session configuration is like bellow (please note the ci_sessions is a writable folder):
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 60*60*1;
$config['sess_save_path'] = APPPATH . 'ci_sessions/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Could you please guide me what is wrong?
Consider for a moment what you are doing.
First you just start the session by calling $this->load->library('session').
Then you immediately stop the session with $this->session->sess_destroy();.
There are multiple problems with what you are trying. Read this to learn more.
You would be much better off simply clearing $_SESSION and then adding the new data to it.
public function index()
{
$this->load->library('session');
// if you want a new session id uncomment the next line, needs to happen before you clear $_SESSION
//session_regenerate_id();
$_SESSION = array();
// if you uncommented earlier then uncomment the next too
//$_SESSION['__ci_last_regenerate'] = time();
$session_data = array (
'key_1' => 'value_1',
'key_2' => 'value_2',
'key_3' => 3
);
$this->session->set_userdata($session_data);
$this->session->set_userdata('key_4', 4);
print_r($_SESSION);
}
With CodeIgniter > v3.0.0 you can set $_SESSION directly. The documentation actually recommends doing it that way. With that in mind the line
$this->session->set_userdata('key_4', 4);
could (should) be written
$_SESSION['key_4'] = 4;
set_userdata() is useful for quickly setting a lot of $_SESSION key/values quickly though.
That said, the following seems less abstract than the earlier code to me. If nothing else, it uses a teeny-tiny bit less memory and avoids a function call.
$_SESSION = array();
$_SESSION['key_1'] = 'value_1';
$_SESSION['key_2'] = 'value_2';
$_SESSION['key_3'] = 'value_3';
$_SESSION['key_4'] = 'value_4';
$_SESSION['__ci_last_regenerate'] = time();
Sorry, I sometimes cannot stop myself from going into lecture mode.
Use:
$this->session->sess_regenerate(true);
Instead of:
$this->session->sess_destroy();

why in Codeigniter my session lost in other pages?

it's first time I use Codeigniter 3.x. after authentication for login I set session data in Login_model.php:
$data_session = array(
'PersonId' => $PersonId,
'PersonEmail' => trim($PersonEmail),
'PersonName' => trim($PersonName),
'PersonFamily' => trim($PersonFamily),
'Login' => true);
$this->session->set_userdata($data_session);
before redirect I have access to my session data by :
print_r($this->session->userdata());
Array([__ci_last_regenerate] => 1510383844 [PersonId] => 129[PersonEmail]=> h#q.com [PersonName] => PersonName [PersonFamily] => PersonFamily [Login] => 1)
but after redirect my session data is something like this:
Array( [__ci_last_regenerate] => 1510384212)
also my setting in config.php is:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'east';
$config['sess_expiration'] = 7200;
//$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
//------------------
$config['cookie_prefix'] = '';
$config['cookie_domain'] = 'domain/admin/';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
I have reviewed a lot of things in this regard. but I still have not gotten a good result.
when using
$config['sess_driver'] = 'files';
then $config['sess_save_path'] must be set to the absolute path of the folder where session files are stored.
With this folder structure
webroot/
application/
sessions/
system/
...etc/
Then
`$config['sess_save_path'] = FCPATH."sessions/";`
will work perfectly.
Folder write permissions must be set appropriately.
EDIT
You should try setting $config['cookie_domain'] = ''; (an empty string) and if that does not work try $config['cookie_domain'] = '.your-domain.com';
The following controller will allow you to test if sessions are working correctly. Create a file named Test_sessions.php in your controllers folder.
Use this code.
<?php
/**
* This class is useful for testing the configuration of the CodeIgniter "session" library.
* It works only for CodeIgniter versions >= 3.0.0
*
* If "session" is properly configured then each time you ask a browser for this page
* the display will alternate between "No session data" and the value of $this->sess_message.
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Test_sessions extends CI_Controller
{
/**
* #var string So you can define your own message to be displayed.
*/
public $sess_message;
function __construct()
{
parent::__construct();
// The next line can be commented out if 'session' is autoloaded - or not, doesn't matter.
$this->load->library('session');
$this->sess_message = "We got session data!";
}
public function index()
{
echo date("F j, Y, g:i:s a")."<br>"; //so you can tell the page actually does refresh
if($this->session->testing)
{
echo $this->session->testing;
unset($_SESSION['testing']);
}
else
{
echo "No session data";
$_SESSION['testing'] = $this->sess_message;
}
}
}
Browse to http://yoursite.com/test_sessions. If sessions are properly configured, every time you refresh the page it will alternate between the two messages.
I solved my problem by change my config to:
$config['sess_driver'] = 'files';$config['sess_cookie_name'] = 'ci_session';$config['sess_expiration'] = 86400;$config['sess_save_path'] = FCPATH.'sessions/';$config['sess_match_ip'] = FALSE;$config['sess_time_to_update'] = 3600;$config['sess_regenerate_destroy'] = TRUE;$config['cookie_prefix'] = '';$config['cookie_domain'] = '';$config['cookie_path'] = '/';$config['cookie_secure'] = FALSE;$config['cookie_httponly'] = FALSE;

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 :)

CodeIgniter(2.1.4) Sessions is not working

I have a problem with CI sessions.
I initialized my session library:
$autoload[‘libraries’] = array(‘database’, ‘session’) (In config/autoload.php)
This is my code:
cycle
$this->load->library(‘image_moo’);
// Upload image and return unique name
$data = array(
‘image’ => $image,
);
$this->db->insert(‘category_images’, $data);
if (!$this->session->userdata(‘uploadImages’))
{
$this->session->set_userdata(‘uploadImages’, $this->db->insert_id());
}
else
{
$session = $this->session->userdata(‘uploadImages’);
$sessionData = $session.’|’.$this->db->insert_id();
$this->session->set_userdata(“uploadImages”, $sessionData);
}
echo $this->session->userdata(‘uploadImages’); // return 256; corect result - 255|256
end of cycle
This is script for image upload with jQuery File Upload (blueimp) and i need set ids of inserted in database images to session.
Can anyone help. Thank you!
To use CI Session you also need to provide the encryption key in your application/config.php:
$config['encryption_key'] = 'xxxxxx';`
Try this
cycle
$this->load->library(‘image_moo’);
// Upload image and return unique name
$data = array(
‘image’ => $image,
);
$this->db->insert(‘category_images’, $data);
if ($this->session->userdata(‘uploadImages’)=='')// or if (!isset($this->session->userdata(‘uploadImages’)))
{
$this->session->set_userdata(‘uploadImages’, $this->db->insert_id());
}
else
{
$session = $this->session->userdata(‘uploadImages’);
$sessionData = $session.’|’.$this->db->insert_id();
$this->session->set_userdata(“uploadImages”, $sessionData);
}
echo $this->session->userdata(‘uploadImages’); // return 256; corect result - 255|256
end of cycle

CodeIgniter Session - i am not getting my userdata in other controller

here is my code to set session
$login_data = array('logged_in'=>TRUE, 'user_id'=>$userid);
$this->session->set_userdata($login_data);
redirect('dashboard');
above code creates a new entry in ci_session table in my db and it has logged_in value
In dashboard controller i am checking session. Below is my code in dashboard controller
function __construct(){
parent::__construct();
$logged_in = $this->session->userdata('logged_in');
if(!$logged_in){
redirect("welcome");
}
}
In above constructor block i am not getting the value of logged_in.
I have also tried to print all my userdata using var_dump($this->session->all_userdata) but all I get is an empty string.
Please tell me what could be the reason behing it. I also searched for cookie but i didn't find that in my computer. below is my config detail
$config['sess_cookie_name'] = 'ci_session';
$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'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
I have solved my problem. I just forgot to change my Cookie Related Variables in config. –
My first guess is being you're doing this in the __construct method which is executed when the class is initialized - before the page is even loaded and your sessions data is set.
$logged_in = $this->session->userdata('logged_in');
if(!$logged_in){
redirect("welcome");
}
Will work if you add in into the beginning of the page method.
Is the library being autoloaded? Check config/autoload.php:
$autoload['libraries'] = array('database', 'session', 'form_validation');
Or call $this->load->library('session'); right before using the class.

Resources