Session destroy in codeigniter - php

I am using Code igniter for my application. I have three controllers and three models in may application homepage,dashboard and settings.I have started the session in homepage model and wanted destroy it in dashboard controller. here is my code
foreach($query->result(as $row) {
$info = array(
'loginid' => $row->loginid,
'firstname' => $row->firstname,
'emailid' => $row->emailid,
'logged_in' => TRUE
);
}
$this->session->set_userdata($info);
but my session array is not getting displyed in dashboard controller.
How I should destroy the session?

Try this:
$this->session->sess_destroy();

You destroy the session with:
$this->session->sess_destroy();
as per the codeigniter session documentation.
That said, I'm not sure how it's related to the code you posted and I'm pretty sure it won't work.

foreach($query->result(as $row) Wrong
Please use
foreach($query->result() as $row)
{
$info = array(
'loginid' => $row->loginid ,
'emailid' => row->emailid,
);
}
To display in dashboard controller. Try this
$this->session->set_userdata($info);
Then you can destroy session by
$this->session->sess_destroy();

$this->session->set_userdata([
'logged_in' => TRUE
'loginid' => $row->loginid,
'firstname' => $row->firstname,
'emailid' => $row->emailid,
]);
And in your conntroller to unset like this
$this->session->set_userdata([
'logged_in' => false,
'loginid' => null
]);

Related

CodeIgnigter - How to store and access user login session

I have a controller that is used to create a user login session with the following code:
public function account(){
$data = array();
if($this->session->userdata('isUserLoggedIn')){
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//Create session
$newdata = array(
'username' => $user['name'],
'email' => $user['email'],
);
$this->session->set_userdata($newdata);
//load the view
$this->load->view('templates/header', $data);
$this->load->view('pages/home', $data);
$this->load->view('templates/footer', $data);
//redirect('pages/view/');
}else{
redirect('users/login');
}
}
Problem occurs when I try to check from this or any other of my controllers the session data and it always returns false. Not sure what it is that Im doing wrong. If I pass this
$data['user']
to a View as data, Im able to access the name and email, but I cant access it on the controller
If I understand correctly I believe your problem is here.
$newdata = array(
'username' => $user['name'],
'email' => $user['email'],
);
The variable $user has not been set in the controller, at least not in the code you show. I think this is what you need
$newdata = array(
'username' => $data['user']['name'],
'email' => $data['user']['email'],
);
A suggestion, not related to your problem, regarding getting session data. With CI >= v3.0.0 you can obtain an item of session data like this.
$this->session->isUserLoggedIn;
The code behind this method is smaller and you type less to get the same return that $this->session->userdata('isUserLoggedIn') provides.
userdata() is a legacy method kept only for backwards compatibility with older applications.
First, you need store session data
`
$sedata = array(
'user' => 1,
'username' => $username,
'userid' => $dbrow->id,
'mobile_phone' => $dbrow->mobile_phone,
'success' => 'Successfully loggedin!',
'logged_in' => TRUE
);
$this->session->set_userdata($sedata);
**Now you get session data like :**
$this->session->userdata('user');
$this->session->userdata('userid');
`

How to edit a session after it's created

I'm using Phalcon PHP and I want to add another item to my session after it's created. I have this :
private function _registerSession($user, $account) {
$this->session->set('auth', array(
'user_id' => $user->id,
'username' => $user->name
)); }
In another controller I want to edit this session for example :
$auth = $this->session->get('auth');
$auth->add('account_id', '10');
And this session will content the 3 variables as :
$this->session->set('auth', array(
'user_id' => $user->id,
'username' => $user->name,
'account_id' => 10
)); }
But I don't know how I can dot that.
Yo need to do it in following manner:-
$auth = $this->session->get('auth'); // get auth array from Session
$auth['account_id']= '10'; // add new index value pair to it
$this->session->set('auth',$auth); // reassign it to auth index of Session
This should work:
$auth = $this->session->get("auth");
$this->session->set("auth", array_merge($auth, array('account_id'=>'10')));
i think you can use like this :-
$auth = $this->session->get('auth');
$auth['account_id']= 10;
$this->session->set('auth',$auth);
private function _registerSession($user, $account) {
$this->session->set_userdata('auth', array(
'user_id' => $user->id,
'username' => $user->name
)); }
// You should use the following code to set one more parameter in sesssion:
$this->session->set_userdata('auth', array(
'user_id' => $this->session_userdata('user_id'),
'username' => $this->session_userdata('username'),
'account_id' => 10
));
Phalcon's session code is simply a wrapper around $_SESSION. The simplest solution is to avoid using Phalcon functions:
$_SESSION['auth']->add('account_id',10);

Yii2 Session persistance when redirecting from one action to another

Using Yii2 framework:
The code below creates an endless loop.
Can anyone please explain how I make the session data persist on redirect ?
I have checked and there is not data being transferred, but the session data is set inside searchuser correctly.
public function actionSearchUser()
{
$session = \Yii::$app->session;
$session->open();
$session->set('admin.currentuser.id', "This worked out ok");
return $this->redirect(['site/modify-user']);
}
public function actionModifyUser()
{
$session = \Yii::$app->session;
$session->open();
if( !($session->has('admin.currentuser.id')) )
{
return $this->redirect(['site/search-user']);
}
else return $this->render('modifyUser');
}
And here is where I setup my session:
'session'=>array(
'class' => 'yii\web\Session',
'name' => 'SESSIONNAME',
'timeout' => 86400,
'savePath' => '/path/to/sessions',
'useCookies' => true,
'cookieParams' => array(
'lifetime' => 86400,
'path' => '/',
'domain' => 'localhost',
),
),
My problem was the domain (I know, I'm stupid).
I have a custom domain (n099y.local) so I needed to change the cookie domain from localhost to n099y.local and everything was fine.
It was showing all the correct session data on the page until I went to another page when the data was again missing because the cookie domain did not match the domain I was on.

Zend 2 Session - destroyed when double click "Enter"

I got problem with Zend 2 session
When I 'quickly' double click 'Enter' in _POST form ( twice submit form before first respond) session is destroyed. When I submit 'in normal speed' all is OK.
My session configuration is exact copy of this http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
only difference is
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'myapp',
'remember_me_seconds' => 3600, //60 min session
'use_cookies' => true,
// 'cookie_httponly' => true, -> not working with Zfc-user subdomain
'cookie_domain'=>'domain.com',
),
),
'storage' => 'Zend\Session\Storage\SessionArrayStorage',
'validators' => array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
In controler I have:
const NAMESPACE_REGORG = 'initialized';
protected $_sessionRegContainer;
public function packageAction() {
//check if user login and redirect
if ($this->zfcUserAuthentication()->hasIdentity()) {
//some staff here
}
//save value to session
$package = $this->getEvent()->getRouteMatch()->getParam('id');
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
$this->_sessionRegContainer->package = $package;
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
public function loginAction() {
//restore session
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
//create form staff.. if submited by double click session is loosing
//value of $this->_sessionRegContainer->package
}
Page use Doctrine 2 ORM , Zfc-user module for authentication and sub-domain for all Zend 2 related content - main domain.com is static html.
It is worth to mention that when I use simple new Container() session with out all setup from Zend page - session work fine with 'double click' but zfc-user stop to work :(
Any idea why session is destroyed? Any help will be appreciated
I sorted it by removing
$session->start();
$session->rememberMe();
from Zend 2 exmple setup -> http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
Double click session destroy ended (fixed).
ps. It look like they already remove rememberMe() from exmple.
Thanks for all help!

Cakephp testing login

I want to test login function if it works propperly and only lets valid and active users in.
My user fixture contains:
array(
'password' => '*emptyPasswordHash*', // empty password
'username' => 'Lorem',
'balance' => 0,
'currency' => 'USD',
'id' => 1,
'user_group_id' => 3, //Customer
'active' => 1,
'hash' => 'LoremHash'
),
My test function looks like this:
function testLogin() {
//test valid login
$result = $this->testAction('/users/login', array(
'data' => array(
'User' => array(
'username' => 'Lorem',
'pass' => '',
'remember' => true
)),
'method' => 'post',
'return' => 'view'
));
debug($result);
}
The login form has 3 inputs: username, password and remember
I have set $this->Auth->autoRedirect = false; in the UsersController::beforeFilter and I am doing some cookie setting stuff
when I debug($this->data); in UsersController::login() it shows the exact same data when testing and when logging normaly. But while testing the login fails and I get $this->Auth->loginError message instead of a login.
How do I test login action propperly?
if you use cakes Auth component and dont hack it up you dont need to...
https://github.com/cakephp/cakephp/blob/master/cake/tests/cases/libs/controller/components/auth.test.php#L545
and if you really want to, look at how the pro's do it :)
Did you also set your custom function, like described in The CakePHP manual:
Normally, the AuthComponent will
attempt to verify that the login
credentials you've entered are
accurate by comparing them to what's
been stored in your user model.
However, there are times where you
might want to do some additional work
in determining proper credentials. By
setting this variable to one of
several different values, you can do
different things.

Categories