2012-10-15 57 views
2

從我的應用程序視圖中,我需要以編程方式註銷當前用戶並在此之後登錄另一個用戶。如何以編程方式重新創建php yii會話?

我想登錄第二個用戶到他自己的不同CHttpSession(與另一個sessionID等)。我出於安全原因需要它。

如何在Yii框架中實現這個?

下面的代碼

$ oSession-> destroy(); $ oSession-> open();

不能按預期工作..

+0

重新創建會話必須在任何輸出到客戶端之前。如果你創建會話,輸出一些數據 - 重建會話將無法正常工作。在輸出一些數據之後,您必須創建會話,刪除會話並重新創建會話。或者你必須使用緩衝輸出 – Sergey

回答

5

貌似你試圖impersonate users

  1. 創建您的UserIdentity功能,將alow您登錄另一個已知用戶:

    protected function logInUser($user) 
    { 
        if($user) 
        { 
         $this->_user = $user; 
         $this->_id=$this->_user->id; 
         $this->setState('name', $this->_user->name); 
         $this->errorCode=self::ERROR_NONE; 
        } 
    } 
    
  2. 在您的控制器中,調用此函數來獲取UserIdentity對象,然後使用Yii的CWebUser登錄

    $ui = null; 
    $user = User::model()->findByPk($userId); 
    if($user) 
    { 
        $ui = new UserIdentity($user->email, ""); 
        $ui->logInUser($user); 
    } 
    Yii::app()->user->login($ui, 0); 
    

記住要保護這個控制器的動作從非授權用戶。

+0

這正是我所期待的! –

0

一種可能取巧的辦法(測試):

session_unset(); 
Yii::app()->user->id = $the_new_id; 

在執行上面的代碼,沒有任何可見的發生在網頁上,所以你可能需要將瀏覽器重定向:

$this->redirect('somewhere'); 

一旦下一頁加載時,具有$ the_new_id的用戶將被登錄