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
Related
I have a User entity on my project.
Each page load, I bother to recover the user with a query in the database.
My goal is to put it in session variable directly after it has logged in to simply get it back when I want.
In my code, if I test this:
$user = $this->checkBDD($mail,$fredurne,$nomComplet);
dump($user);
$this->session->set('user',$user);
$user = $this->session->get('user');
dump($user);
I have :
So, the session seems work.
Now, I put it into application. I create a function:
$user = $this->getUtilisateur($mail,$fredurne,$nomComplet);
dump($user);
With
public function getUtilisateur($mail,$fredurne,$nomComplet)
{
if(!$this->session->has('user'))
{
dump("user not in session");
$user = $this->checkBDD($mail,$fredurne,$nomComplet);
$this->session->set('user',$user);
}
else
{
dump("user in session");
$user = $this->session->get('user');
}
return $user;
}
And I have :
So, I don't understand what's the problem
Problem :
Doctrine entity is stored on session but needs to be refreshed
But when you retrieve the entity from session : Doctrine unit of work does not know it have to handle this entity
After that you should have some issues with Doctrine lazy loading.
Session is not good to store an entity.
A better solution is :
Inject Doctrine entity manager in your service
Only store id on session
On getUtilisateur method retrieve the user with id if not already done
i'm trying to add arrowchat, an tchat box from arrowchat.com And these file is just using php without using twig in my website and i don't know how to do for integrate this file with my session variable from twig.
This is what i need to do for integrate these file:
First, open the arrowchat/includes/integration.php file. This file must be customized to fit your specific website.
get_user_id() Function
The first and most important function to setup is the get_user_id() function. This function will simply return the user's ID or NULL if no user is logged in. The two most common ways to setup this function are by cookie and session.
Using a Session example:
function get_user_id()
{
$userid = NULL;
if (!empty($_SESSION['userid']))
{
$userid = $_SESSION['userid'];
}
return $userid;
}
My problem is:
It's not working and i think it's because $_SESSION['userid'] doesn't exist.
How can i do for take the user id from my session without using twig?
I'm using FOSUserBundle for making the session when i connect to my website
Thanks all :)
If you are into a controller you can do this with FOSUserBundle:
$user = $this->getUser();
if (null != $user) {
$userid = $user->getId();
}
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.
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());