2013-07-22 30 views
0

我正在爲我工​​作的公司使用的Web應用程序構建替代品。它是使用CakePHP 1.3構建的,我使用Symfony 2從頭開始重寫它。這兩個系統將並排運行,各種功能將傳輸到Symfony 2並從舊的CakePHP應用程序中移除。如何使用Symfony 2讀取Cookie?

爲了避免與登錄細節混淆,我希望CakePHP處理用戶登錄事物,直到我可以完全關閉CakePHP並依賴Symfony 2的安全性。與此同時,CakePHP應用程序生成一個包含用戶ID的cookie。我想用Symfony的這個cookie作爲基本的安全形式。

但是,我無法讓Symfony讀取或加載已創建的cookie。這裏是我的代碼:

public function securitytestAction() 
{ 

    $request = $this->getRequest($_COOKIE); 
    $cookie = $request->headers->getCookies('CakeCookie[passport]'); 

    print_r($cookie); 

    return $this->render('InstructorBundle:Default:test.html.twig'); 
} 

使用Firebug,CakePHP在登錄過程中生成的Cookie名爲'CakeCookie [passport]'。它也沒有加密。

我得到的錯誤是這樣的:

FatalErrorException: Error: Call to undefined method Symfony\Component\HttpFoundation\HeaderBag::getCookies() in DefaultController.php line 713

我能做得到這個工作?

編輯
Cheesemacfly曾建議更換:

$request = $this->getRequest($_COOKIE); 
$cookie = $request->headers->getCookies(); 

通過如此:

$request = $this->getRequest()->cookies->all(); 

我得到如下回應:

Array ([PHPSESSID] => gptbmh61mfkqn6p86d3suhnt13)

編輯2
我一直在尋找CakePHP用來生成Cookie的代碼,它沒有給出cookie的域名。我現在已經修復了這個問題,以便域名是.domain.org,這樣子域名也可以訪問它。

現在,當我使用Firebug訪問Symfony2應用程序時,我可以看到Cookie與其他兩個CakePHP會話cookie(我不需要)一起列出。即使在查看子域new.domain.org時,3個CakePHP域也都使用www.domain.org,而Symfony2使用的一個cookie顯示域名爲new.domain.org .Symfony2雖然仍然拒絕加載我想要的Cookie。

+0

如果你不帶參數調用'$ request-> headers-> getCookies()'會怎麼樣? – cheesemacfly

+0

我得到同樣的錯誤@cheesemacfly,我會相應地改變問題先生。 – mickburkejnr

+0

如何使用'$ this-> getRequest() - > cookies-> all()'?或'$ this-> getRequest() - > cookies-> get('CakeCookie [passport]')'? – cheesemacfly

回答

1

我想通了一位朋友的幫助。

本質上,在CakePHP中設置的cookie不包含路徑。爲了解決這個問題,我添加了下面的PHP代碼:

$value = $someone['User']['id']; 
setcookie("passport", $value, time()+1200, "/", ".domain.org"); 

我再檢查Symfony2中,在不改變從以前的編輯代碼,然後Symfony2中可以拿起餅乾。

謝謝大家的幫助!

0

在每次請求期間,Symfony2默認會在Twig和PHP模板引擎中設置全局模板變量應用程序。該應用程序變量是GlobalVariables實例,它將讓您使用自動某些應用特定的變量:

app.security - The security context. 
app.user - The current user object. 
app.request - The request object. 
app.session - The session object. 
app.environment - The current environment (dev, prod, etc). 
app.debug - True if in debug mode. False otherwise. 

例子: 在樹枝:{{app.request.method}} 在PHP:回聲$ APP-> getRequest() - > getMethod()在twig中:{{app.user.username}} 但對於會話對象: 在twig中:{{app.session.varname}} 在PHP中://我不知道,你知道怎麼稱呼它嗎?