user session confusion in symfony 2 - php

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.

Related

Sessions in symfony2

As follow user sessions in Symfony2 , as is the way of working with sessions?
I need to keep the user session by Symfony2 for example, use their name, or that I have some data stored in a database . As recommended me to work ?
im using symfony 2.4
thanks
In your controller, you can access session via
$session = $this->getRequest()->getSession();
$session->set("username", $username);
// ... later
$username = $session->get("username")
A more real-life example is one I use to show a banner only once per visit.
public function bannerWidgetController(Request $request)
{
$session = $request->getSession();
if ($session->get('banner-visited', false))
{
return new Response();
}
$session->set('banner-visited', true);
return $this->render('widget/banner.html.twig');
}
Then I include this in my TWIG via the "renderController" method.
As your question is a bit hard to understand I don't know if it is exactly what you want but there is already a mechanism included in Symfony2 to store sessions in database.
There is a simple guide you can follow here :
http://symfony.com/doc/2.4/cookbook/configuration/pdo_session_storage.html

Do I need to start the session at any controller where I need to access it?

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.

Can I handover sessions from Laravel to my simple MVC?

I just want to know if I am able to hand over session variables from Laravel to my custom code. What I mean is: I want to handle log-in through Laravel and pass it to my profile section which is not in Laravel. Most of the routes are handled by a .htaccess file. The goal is to just login with Laravel auth and save that to $_SESSION['user'] var and redirect to /profile. Somehow I don't get that. The session name is the same in both, in Laravel's session.php's cookie name and my custom code's constant. Is there any other factor I should consider ?
Okay here's the code:
namespace Services\Session;
class OldSessionAuth
{
protected $auth;
function __construct()
{
$this->auth = \Auth::user();
}
public function setSession()
{
$_SESSION['user'] = $this->auth->toArray();
$_SESSION['auth'] = 'TRUE';
return true;
}
public function destroy()
{
session_destroy();
session_unset();
}
}
So, this is sort of my Session services, which is initialized only if it passes the Auth from the controller, Now I think I don't need to do that. so I skiped it, Basic Stuffs (Auth::Check()) really. So, I'd just do this in my login method.
$old = new Services\Session\OldSessionAuth();
$old->setSession();
return Redirect::to('/');
The home page is controlled by my custom made MVC and I want to grab the session, which in this case I can't. It shows Array(). There is no session manipulation when retrieving the session.
Laravel already has a pretty good session abstraction so I don't think you needed to use session_start(), $_SESSION etc directly. Sharing an session across two applications is a bit tricky. If you are tied to using the cookie approach, then you have to make sure that the session driver in use is the cookie one. You would also need to ensure that the restrictions on the cookie aren't such that your other application isn't being sent them by the user's browser.
By default, PHP will use a file cookie driver. In this case, what you would have to do in your other application is to read the "PHPSESSID" cookie, set the session ID using session_id() to this and only then would you have access to the session data using the $_SESSION variable in the other application.
This is all pretty hacky though. I would recommend that if you need to share sessions that you make use of a database session driver instead. This way, you are able to share arbitrary session data across applications using a standard interface. In this case, you would just read the "laravel_session" cookie instead to be able to look up the session in the database. There would be many hidden pitfalls if you then wanted to also modify this data from the other application as well though.

How to clear a session container in Zend framework2

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());

How to set and destroy sessions in PHP Symfony

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

Categories