Session doesn't hold custom userdata - php

I'm new to CodeIgniter and I started to use the session library.
I have autoloaded the session library and trying to save the current user_id to the session userdata array. But the information is gone when I try to read it on an other page..
The native PHP sessions work just fine (tested it), so it must be something from CI.
I programmed a simple test page where I test the following:
Set the session userdata.
Test page shows the userdata correctly.
Uncomment the set session data lines in the code of the controller and reload the page.
Test page doesn't show the userdata.
The code of the controller:
class Welcome extends CI_Controller {
public function index(){
$data = null;
$data['test'] = "Yeeeeh!!";
$this->session->set_userdata($data);
$this->load->view('welcome_message', $data);
}
}
Code of the view:
<?php
echo $this->session->userdata('test');
?>

Why does the view display the session_id and not the "test" variable you created?
Did you test
<?php
echo $this->session->userdata('test');
?>
in the view file?

CI's sessions are cookies, not PHP native sessions. Calling sessions in a view works (IIRC), but since your view is loaded in the same request the session is created, it won't be set.
You need to call it on another request (i.e. another controller), or set the session somewhere else (in another controller, via AJAX could work also), or use native PHP $_SESSION array instead.
I think your actual code is just a test case, otherwise why not just
public function index(){
$data = null;
$data['test'] = "Yeeeeh!!";
$this->session->set_userdata($data);
$this->load->view('welcome_message', $data);
}
in view:
<?php
echo $test;
?>

Related

Passing information between pages with Laravel

I need to pass information between pages.
I would usually just use sessions in plain PHP. I wonder if there is a more correct way to do this on Laravel.
First_page.php
<?php
session_start();
$_SESSION["ID"] = 'item_id';
?>
Second_page.php
<?php
session_start();
echo $_SESSION['ID'];
#"item_id"
?>
How is this supposed to be done in Laravel?
Just use Session.
Session::flash(); //or Session::put
Session::flash('values', $passvalues);
Redirect::to('/add1');
$oldinput = Session::get('values');
In laravel you can pass a variable in your url i.e. :
In routes.php
Route::get('/page1', 'YourController#Yourfunction');
Route::get('/page2/{id}', 'YourController#loadpage2');
In your controller.php
public function Yourfunction(){
return view('page1');
}
public function loadpage2(id){
return view('page2', compact('id'));
}
in your view have a link to url /page2/3 where 3 is your id
If you want to use session then you need to do 2 things.
save session variables in your controller
display session variables in your view
In your controller you can use something like
session()->put('your_session_variable','some value');
In your view then you can display that session variable
#if(session()->has('your_session_variable'))
{{Session::get('your_session_varible',"session_not_set(default value)") }}
#endif
Its good to use default value for displaying session variables (many times that session variable is not set).

The Auth component still fetching older value of Session?

I am manually modifying some key of Auth session in beforeFilter of AppController.php by this code
public function beforeFilter(Event $event){
//$companyId = $this->Companies->find(.........
$this->request->session()->write('Auth.User.company_id', $companyId);
}
And in various actions of different controller i'm trying to get that stored companyid in session by following way
public function add(){
$companyId = $this->Auth->user('company_id');
debug($companyId); die;
}
When i see the value of $companyId, it is showing older value not updated one in beforeFilter method of AppController. However if i refresh the page and donot modify session again i will get updated $companyId value.
So my question is how can i update the value of Auth session data so that i can get updated value with $this->Auth->user('company_id') code in different places in same request?
The session storage used by the authentication component uses a buffering mechanism, ie the value from the session is usually only read once per request (unless it is being deleted/emptied).
https://github.com/cakephp/cakephp/blob/3.2.8/src/Auth/Storage/SessionStorage.php#L81-L83
So either read the value directly from the session in your controller action, or do not write to the session directly, but to the session storage, something along the lines of
$user = $this->Auth->user();
if (is_array($user) && $user) {
$user['company_id'] = $companyId;
$this->Auth->setUser($user);
}

Codeigniter session generates new session on every page

On every page I see that new session is generated with null userdata
On model constructor
$this->config->set_item('sess_table_name', 'xx_sessions');
Because I want to store this session in another table because the other session table is being used for another login activity
Login function
function login($username,$password)
{
$this->db->where('login',$username);
$this->db->where('pass',$password);
$q=$this->db->get('prof');
// print $this->db->last_query();
if($this->db->count_all_results())
{
$arr=$q->row();
// creating the session
$this->session->set_userdata('login',$arr->id);
$this->session->set_userdata('prof',$arr->profile_id);
// print_r( $arr);
}
else
return FALSE;
}
This login function is on a model. After login and generating the session the page redirects to another page, on that page I see the session builds without any problem but when I move to another page the session losses along with the userdata.
I use the following function to check session data
function print_session()
{
print_r( $this->session->all_userdata());
}
Where I'm wrong ? Tank_auth library and ion_auth library works fine .. I had already used the
Put the session library name into the autoloader configuration, in application/config/autoload.php:
$autoload['libraries'] = array('session');
Then it's available automatically in each controller and everywhere in your application and you get your session data from anywhere:
$session_id = $this->session->userdata('session_id');
And if you don't want to auto load session library then you have to initialize the Session class manually in your controller constructor, use the $this->load->library function:
$this->load->library('session');
For details have a look here:http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Edit /application/config/config.php and set cookie domain variable
$config['cookie_domain'] = ".yourdomain.com";
It will work!
.yourdomain.com makes the cookie available throughout the domain and its sub-domains.
I have met same problem, and i have searched lots of pages.
I figured out that changing sess_cookie_name solves the problem(new sessions generating issue)
$config['sess_cookie_name'] = 'somenewname'

Yii setFlash with Logout

Im tying to use the command sequence:
Yii::app()->user->setFlash('success', "Successful!");
Yii::app()->user->logout();
$this->redirect(array('user/login'));
The user got logged out and redirected, but the Setflash does not work.
I also tried to change the order of 2 frist commands, but got the same problem.
If I do not logout the user, the Setflash works fine.
How can I make both commands work?
this should work
Yii::app()->user->logout();
Yii::app()->session->open();
Yii::app()->user->setFlash(...);
If you need to destroy a whole session but you want to set a flash afterwards, you may extends CWebUser this way:
<?php
class BaseWebUser extends CWebUser
{
public function logout($destroySession = true)
{
parent::logout($destroySession);
Yii::app()->session->open();
}
}
?>
have a closer look here
I think you can use this :
public function afterLogout() {
// Create new session
$session=new CHttpSession;
$session->open();
// Set flash message
Yii::app()->user->setFlash('success', 'You are logged out successfully.');
// Prepare target URL after logout
$continue_url = Yii::app()->request->hostInfo . Yii::app()->createUrl('');
// Redirect
CController::redirect($continue_url);
}
Put it inside your WebUser components.
Flash messages are stored in the session. Logging the user our destroys the user's current session. Once session_destroy() is called, you must call session_start() again in order to generate a new session ID and have this work. Yii most likely does not do that.
If it's that important that you have a "Successful" message indicating that the logout worked - then redirect the user to a "logout successful" page. Alternatively, you can look into overriding the way Yii performs a logout - although I wouldn't recommend it.

Logout codeigniter

I have a logout controller in codeigniter :
<?php
class Logout extends MY_Controller {
function index()
{
$this->session->sess_destroy();
redirect('index.php');
}
}
This logs me out but when i call another controller after logging, like "/site/addnewpost",
this just logs me in again, as if the sassion had not been destroyed previously. Why is this happening?
Follow ALex's suggestion, but using CI code:). What I mean, try unsetting each session data individually. I read once about an issue in version 2.0.3 I think, but I don't remember now and I don't have time to search for the reference. It's in their forum, though, and the suggestion was the same: unset each session element one by one.
$this->session->unset_userdata('data_one');
$this->session->unset_userdata('data_two');
$this->session->unset_userdata('data_three');
$this->session->unset_userdata('data_one');
$this->session->sess_destroy();
redirect('home','refresh'); // <!-- note that
//you should specify the controller(/method) name here
You need to redirect because CI's session are just cookies, not the native php session array.
Another thing...make sure the fault isn't in your login methods, which logs you in no matter if you succesfully logout or not!
Try explicitly delete items like this:
$this->Session->delete('User');
$this->Session->destroy();
$this->Cookie->delete("User");
$this->Cookie->destroy();
$this->Auth->logout();
$this->redirect('whereever');
My problem had to do with caching on the server side. The quickest I could fix it was by appending random text to the logout link:
<?php
$this->load->helper('string');
echo anchor('/home/logout/'.random_string(), 'logout');
?>
home/logout contained the same code as function index in the question.
Just so you know the redirect('/', 'refresh') did not work for me, but I again I did a quick test.
I am guessing that the random_string() method can be replaced by outputting headers that force cache to be cleared etc. As you have probably guessed, I can't do that right now as I am super busy. Maybe later.
You can also try manually setting your "logged_in" or whatever you called the session to false. Then, destroying all other session data.
$this->session->set_userdata('logged_in', FALSE);
$this->session->session_destroy();
redirect('index');
first we have to load session library to deal with session than unset the sessionID and destroy the session. I am using this code to unset my session and secure logout.
$this->load->library('session');
$this->session->set_userdata('user_id', FALSE);
$this->session->sess_destroy();
$this->load->view('your URL');

Categories