问题描述
Symfony 在每次加载页面时创建一个新会话时遇到问题,而不是跨请求传输数据.config.yml 中 session 部分的 auto_start 设置为 false,常规 php 会话工作正常.只有在 symfony 中运行时才会出现问题.
I'm having a problem with Symfony creating a new session on each page load, rather than carrying data across requests. The auto_start in the session section in the config.yml is set to false, and regular php sessions work fine. It's only when running in symfony that I get the problem.
例如,我创建了测试操作:
For example, I created the test action:
public function sessionTestAction()
{
$s_Response = '<html><head></head><body><p>Foo</p></body></html>'; //Initialize response and headers
$a_Headers = array();
$i_StatusCode = 200;
$oSession = $this->get('session');
var_dump($oSession->all());
if(!$oSession->has('Test'))
{
$oSession->set('Test', 'Bar');
}
$oSession->save();
return new Response($s_Response, $i_StatusCode, $a_Headers);
}
预期的操作是,在第一个页面加载时,var_dump 不会产生任何结果,并且在任何后续执行中,它将包含 Test=>Bar.但是,它永远不会跨请求获取这些数据.
The expected action is, that on the first page load, the var_dump will yield nothing, and that on any subsequent executions, it will contain Test=>Bar. However, it never gets that data across requests.
此外,它还为每个请求创建一个新的会话 ID.
In addition, it creates a new session id for each request.
我使用的是 Symfony v2.0.15 和 PHP v5.4
I am using Symfony v2.0.15, and PHP v5.4
有人有什么想法吗?
我觉得我取得了一些进步.我对测试操作进行了以下更改:
I made some progress, I think. I made the following changes to the test action:
public function sessionTestAction()
{
//Initialize response and headers
$oRequest = $this->get('request');
$a_Headers = array();
if (isset($oRequest->headers->all()['cookie']))
{
$a_Headers['Set-Cookie'] = $oRequest->headers->all()['cookie'];
}
$i_StatusCode = 200;
$oSession = $oRequest->getSession();
$oSession->start();
$s_Response = print_r($oSession->all(), true);
if(!$oSession->has('Test'))
{
$oSession->set('Test', 'Bar');
}
$oSession->save();
$oResponse = new Response($s_Response, $i_StatusCode, $a_Headers);
return $this->render('Bundle:Default:index.html.twig', array('response' => $s_Response), $oResponse);
}
那个树枝文件只有{{response|raw}}.它现在为 3 个请求中的 2 个保持会话.然而,在第三次请求时,它被清除了.
Where that twig file has just {{response|raw}}. It now holds the session for 2 out of 3 of the requests. However, on the third request, it's cleared.
推荐答案
原来的问题是,有人在 app.php 运行时添加了一行来设置会话 cookie,不知道 symfony 自己处理会话,我猜.问题解决了.
Turned out the problem was, someone added a line to set a session cookie whenever the app.php was run, not knowing that symfony handled sessions itself, I guess. Problem solved.
这篇关于Symfony2 没有正确保存会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!