How to set and destroy a session on the controller side?
Tried in the view side, works just fine. But now need it from inside the controller.
UPDATE:
Destroy a Session in Symfony 2 as follows:
$request->getSession()->invalidate(1);
As invalidate leaves the current session untouched if you are not providing any parameter you have to set the lifetime on 1 (one second)
Symfony 3.4 documentation:
http://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Session/Session.html#method_invalidate
Did you try?
/** #var $session Session */
$session = $request->getSession();
$session->remove('name');
Did you try
$this->getAttributeHolder()->remove('foo');
if it was saved in namespace foobar
$user->getAttributeHolder()->remove('foobar','','foo');
At last I found the solution just here around. Use the "session" service explained here: Old post
Related
I have upgraded my codeigniter 2.x to 3.0 and I am facing session issue. My site has multi language support so I want to keep language session even when user logout from account. I have implemented logout functionality as mentioned below.
$lang = $this->session->userdata('language');
$this->session->sess_destroy();
$this->session->sess_create();
$this->session->set_userdata(array('language' => $lang));
As CI 3.x sess_create() has been removed so I'm unable to create language session after destroying session. I know we can use cookies helper instead of session but I need to make many changes if I have to use cookies instead of session.
Try below code. Note that here sesssion_var is a variable name in which you are storing your session
$session = $this->session->userdata('sesssion_var');
$language_session = $session['language'];
$this->session->set_userdata('sesssion_var',$language_session);
Use unset_userdata('sessionnamewhichhastobedestroy') rather than sess_destroy().
Or if you use sess_destroy() then set default value in $lang
I have this code in the indexAction of a controller and that index is a start point for a process (include call to several controllers through Ajax):
$session = $request->getSession();
$currentData = [];
$session->set('currentData', $currentData);
Now suppose that I need to set a new value for currentData in another controller, I'm doing right now as:
$session = $request->getSession();
// get currentData from session for not override the values
$currentData = $session->get('currentData');
// sets the new value
$currentData['newValue'] = 1;
// save the var again and override currentData session
$session->set('currentData', $currentData);
Regarding this and as title says the question is easy: Do I need to start (call $session = $request->getSession() all the time whenever I need access to session) the session at any controller where I need to access it? Exists any best way to achieve this or I'm the one did all wrong? Any advice?
NOTE: I forgot to mention I'm talking and working with Symfony 2.6.3
You don't have to, however it is recommended. From the docs:
While it is recommended to explicitly start a session, a session will actually start on demand, that is, if any session request is made to read/write session data.
You do need to get the Session container by using $session = $request->getSession(), $session = $this->get('session'), or $session = new Symfony\Component\HttpFoundation\Session\Session();. This is not the same as starting a session and there's really no difference between the three ways.
This applies to any Symfony 2.x version.
Example of my code:
class SiteController extends Controller {
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex() {
$_SESSION['test'] = 'testdata';
var_dump($_SESSION); exit;
}
Example on the second request:
class SiteController extends Controller {
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex() {
var_dump($_SESSION);exit;
}
I have a project in yii. Project not mine - I'm just trying to fix errors.
My problem is:
first var_dump() shows that $_SESSION variable HAS the "test" index with "testdata". On the second request though I get an empty array of $_SESSION variable. Meaning, that every request session gets cleaned up. I've checked - the session ID stays the same. I've also checked this projects config - i can't find any references to extending SESSION component and changing it's behaviors. Also, when logging in yii DOES save states into SESSION, but the login fails because of SESSION being cleaned after redirect. That is to say COOKIE BASED authentication works which just proves the root of the problem.
Would very much appreciate help.
UPDATE
I've narrowed it down. This is the code for FRONT YII FRONT CONTROLLER(index.php):
<?php
#session_start(); // this line is at cwebuser.php at init() method and it is called at every request. should work properly.
var_dump($_SESSION);
$_SESSION['test'] = 'asdasd';
var_dump($_SESSION);exit;
It still prints empty $_SESSION on the second REQUEST. So the problem is probably not with the framework.
You can set session details in your /protected/config/main.php (this is the default unless you have changed it in index.html)
'session' => array(
'autostart' => true,
'timeout' => 1440, // time in seconds
),
Read about Session on CHttpSession
My problem was that I accessed my website via server ip : 123.123.123.123/site/index and this has conflicts with accessing and saving the session. Though I don't know the details. If someone has knowledge on this stuff I will gladly accept his(her) answer as the right one.
There is a file called controller.php under protected/components/controller.php which will be called before any action get called .. u can check that file and see... is there done any logout function calledthere...
//It clears all the sesstion data... or any php way
Yii::app()->user->logout();
Yes if u are in moule then u can also check ModuleName.php under module directopry ... if there is any session clearing script...
which clears the session... And yes this is not the right way of using session in Yii yes it is PHP but YII .... u can use folowing sytax dfor sessions..
//to set a session variable mnamed test
Yii::app()->user->setState('test',$test);
//to get a session variable named tets
Yii::app()->user->getState('test');
How can I handle user session in symfony? because I'm reading the book of symfony 2 and it says:
Storing and retrieving information from the session can be easily achieved from any controller:
$session = $this->getRequest()->getSession();
// store an attribute for reuse during a later user request
$session->set('foo', 'bar');
// in another controller for another request
$foo = $session->get('foo');
// use a default value if the key doesn't exist
$filters = $session->get('filters', array());
I wonder how to destroy the session. I'm a newbie in symfony so please explain. I'm confused because I found a thread that says its not the way to handle user sessions in symfony2 http://forum.symfony-project.org/viewtopic.php?f=23&t=42766
The link you pointed to is how it used to be until Symfony 2.2 (I think) - that is, it is outdated. Which exact version do you have installed?
You create session by:
$session = new Session();
If you want to invalidate whole session:
$session->invalidate();
of just single value:
$session->remove('some_key');
You can find complete API of Session here.
I have recently started building an application using Zendframework 2 , I have good experience in ZF1 , the major problem I am facing here with ZF2 is with sessions .
Here is the way that I am creating a session container .
use Zend\Session\Container;
// Session container creation: ( previously we were calling it as namespaces )
$session_user = new Container('user');
$session_user_errors = new Container('usererrors');
$session_user_shares = new Container('usershares');
Now Like this I have several containers ,
I could clear a key of a particular container like this
// Getting value from the session by key: ( get value from namespace )
$email = $session_user->offsetGet('email');
// Setting value in session: ( set value from namespace )
$session_user->offsetSet('username', 'abcd');
Now my problem is to clear an entire container which are set in several levels of my application .
If I try the below code Its clearing all of my session containers .
$session_user = new Container('user');
$session_user->getManager()->getStorage()->clear();
I want to clear only the container called 'user' which has many keys ( I dont know what all will be there at end ) . Is there a way to achieve this
I know I can do offsetunset on each key but thats not an Optimal solution I feel .
Please kindly suggest if any alternative way is there to clear a particular session container .
NOTE : - I am not using any of the third party modules like ZfcUser and Akrabat sessions
Thanks in advance for responding to this posting .
You almost had it, you just need to pass the namespace to the clear method
$session_user->getManager()->getStorage()->clear('user');
You can still treat the $_SESSION like an array, too, so the following also works
unset($_SESSION['user']);
The Solution posted By #Crisp worked like a Charm But here is the alternative way what I found after a research to solve this problem
use Zend\Session\SessionManager;
$sessionManager = new SessionManager();
//get array of sessions from storage
$array_of_sessions = $sessionManager->getStorage();
//Unset which ever container you want by passing its name ( ZF1 its called namespace )
unset($array_of_sessions['user']);
unset($array_of_sessions['usershares']);
unset($array_of_sessions['actions']);
I feel session manager is the one that we need to use to manage sessions whether to clear or read and container is one of the entity which is managed by session manager .
This may help others who are possessive in creating objects of each session container and call clear method .
To destroy all the sessions:
$session = new Container('base');
$session->getManager()->destroy();
or
use the simple php destroy function:
session_destroy();
This function clears all the sessions.
I hope this helps.
Following are the details for Destroying the session in Zend Framework 2:
Using Basic PHP Functionality
session_start() function starts the session.
session_destroy() function deletes ALL the data stored in session array.
Now using Zend Framework functionality:
For clear understanding lets first, create a session in Zend Framework and then make a Delete process.
Creating Session
use Zend\Session\Container;
$session_container = new Container('user_session');
$session_container->last_login = date('Y-m-d H:i:s');
$session_container->sess_token = trim(base64_encode(md5(microtime())),
"=");
Deleting Session
$session = new Container("user_session");
$session->getManager()->getStorage()->clear('user_session');
Where user_session is the name of session array key for storing the details.
Container::getDefaultManager()->getStorage()->clear('user');
In ZF2, for Container use;
Create container:
$sessionTokenizer = new Container('token');
Set variable into container
$token = $sessionTokenizer->token;
Destroy container (ONLY CONTAINER)
$sessionTokenizer->offsetUnset();
You can clear session like this:
$this->session->exchangeArray(array());