[英]how to access $_SESSION variable in symfony2
我正在嘗試執行以下操作:
$postfields = array_merge($_SERVER, array("p"=>$_POST, "s"=>$_SESSION));
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, count($postfields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
為什么這不起作用? 它總是給我一個錯誤,提示$ _SESSION不存在。
Symfony使用特殊的會話庫來擴展PHP $_SESSION
接口。 要將所有會話屬性作為key => value
數組訪問,可以使用(從任何控制器/容器):
$all_session_variables = $this->get('session')->all(); // Returns array() format
或使用以下特定會話元素:
$key_session_variable = $this->get('session')->get('key'); // Returns the value stored in "key"
但這只能保證在您以前使用$this->get('session')->set()
設置會話變量的情況下才能起作用。
關於為什么出現“ $_SESSION
不存在”錯誤的原因:您尚未聲明session_start()
! Symfony尚未為您完成此操作。 但是等等 。 不寫,因為上述國家相同的代碼:
Symfony會話旨在替換一些本地PHP函數。 應用程序應避免使用
session_start()
,session_regenerate_id()
,session_id()
,session_name()
和session_destroy()
,而應使用以下部分中的API。
您應該改用Symfony提供的Session庫,因為:
雖然建議顯式啟動會話,但是實際上會根據需要啟動會話,也就是說,如果發出任何會話請求來讀取/寫入會話數據。
要進行會話,請嘗試將其放入您的控制器中:
$session = $this->get('session');
推薦方式(在控制器中):
...
public function testAction(Request $request)
{
$session = $request->getSession();
}
...
或通過注入RequestStack
(在CustomService中):
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function myMethod()
{
$session = $this->requestStack->getCurrentRequest()->getSession();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.