Setstate And Cookie

i read docs, but i can’t store state into cookie and after autologin get value from cookie

i use default yii site




//class UserIdentity extends CUserIdentity

public function authenticate()

	{

		$users=array(

			// username => password

			'demo'=>'demo',

			'admin'=>'admin',

		);

		if(!isset($users[$this->username]))

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		elseif($users[$this->username]!==$this->password)

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else

                {

                        Yii::app()->user->setState('time', time());

			$this->errorCode=self::ERROR_NONE;

                }

		return !$this->errorCode;

	}




public function actionIndex()

	{

		// renders the view file 'protected/views/site/index.php'

		// using the default layout 'protected/views/layouts/main.php'

                echo Yii::app()->user->getState('time');

		$this->render('index');

	}



then i login with checkbox rememberme, actionIndex display "time"

but when i close browser, then open actionIndex i get empty “time” but i’m login

any ideas?

By default, setState() uses session to store data, not cookies. Devs often forget to check how the ability to modify stuff stored using setState affects their application security, so it’s not really safe to use cookies.

See the description of the CWebUser class, where it states:

If you really need to store something more persistent than a session consider using cookies directly via the cookies collection available in CHttpRequest (Yii::app()->request).

i know about cookie, but i want to understand with setState

i set allowAutoLogin=true but it not help, all data in setState not storing in cookie

any ideas?

Did you take a look at the Yii source of CWebUser::setState()?

There is only coded to save a value into the $_SESSION, nothing about cookies.

States are saved to cookie in the saveToCookie method called on login, when duration is greater than 0.

The saveToCookie method only saves the states of the CUserIdentity, not the states of the CWebUser

($this->saveIdentityStates() is called there).

So try to set the state of the identity, not the one of the user:




...

 else

                {

                       // Yii::app()->user->setState('time', time());

                        $this->setState('time', time()); //$this = UserIdentity 

                        $this->errorCode=self::ERROR_NONE;

                }

...