Yii重定向后丢失会话

时间:2013-12-23 12:14:12

标签: php session yii

我有yii项目,Chrome会话丢失了。 例: 在main.php中配置

'session' => array(
            'class' => 'CDbHttpSession',
            'autoStart' => false,
            'connectionID' => 'db',
            'sessionTableName' => 'ph_YiiSession',
            'autoCreateSessionTable' => false    // for performance reasons
        ),
登录后在启动控制器中

我在会话中写入id用户

Yii::app()->user->id = 100

重定向用户

之后
$this->redirect(array('student/index'), true);

但在索引操作中我无法从会话中获取数据

echo Yii::app()->user->id;
什么也没有。请帮帮忙,这个问题已经让我的大脑崩溃了

3 个答案:

答案 0 :(得分:0)

你应该试试

'autoStart' => true,

答案 1 :(得分:0)

Yii::app()->user->id = 100

首先
您无法永久设置 ID ,可以在不同页面中使用。即使您在页面中设置了Id,当您移动到下一页时它的数据也会丢失,并且它将显示其默认值。因此,如果您想更改Yii::app()->user->id包含的值,则必须覆盖getId()方法。

第二件事

如果您尝试在会话中保存ID,则应使用Yii::app()->session['_myId']=Yii::app()->user->id; 然后你可以像

那样得到它
echo Yii::app()->session['_myId'];

并记住'autoStart' => TRUE,

答案 2 :(得分:0)

你做错了肯定在UserIdentity类。从Yii::app()->user->id设置和检索会话数据的最佳方法是覆盖UserIdentity类中的getId()方法。

例如,假设您有一个名为“User”的表,它包含:id,username,password。

所以,让UserIdentity类像这样:

<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{

    private $_id;

    public function authenticate()
    {
        $user = User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
        if($user===null){
            $this->errorCode=self::ERROR_USERNAME_INVALID;

        }else if($user->password !== crypt($this->password,$user->password)){
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        }
        else{
            $this->_id = $user->id;
            $this->username = $user->username;
            $this->errorCode = self::ERROR_NONE;
        }
        return $this->errorCode === self::ERROR_NONE;
    }

    public function getId()
    {
        return $this->_id;
    }
}

一旦你这样做,你应该能够使用Yii :: app() - &gt; user-&gt; id并在你的代码中的任何地方获取会话ID。

希望这会有所帮助。

P.S&gt;我还制作了一个基础应用程序,所有这些都已经完成。您可以在以下位置查看:https://github.com/sankalpsingha/yii-base-app它可能对您有帮助。

相关问题