9

I am trying to set some session variable in Yii using the following code :

    $session=new CHttpSession;
            $session->open() ;
            $session->setSessionName('My Session') ; 
            $session['sleep'] = 0 ;
            $session['attempts'] = 0 ;
            $session->writeSession('sleep','0') ; 
            $session['ip'] = $this->get_ip_address() ; $session->close() ;    var_dump($session,$session['ip']) ; 

However , I am not able to set the session vaiables above , the dump has the following result :

object(CHttpSession)#17 (5) { ["autoStart"]=> bool(true) ["behaviors"]=> array(0) { } ["_initialized":"CApplicationComponent":private]=> bool(false) ["_e":"CComponent":private]=> NULL ["_m":"CComponent":private]=> NULL } string(3) "::1" 

It sees $session and $session['ip'] as two completely different variables . Can someone help me out with this ?

Moe Far
  • 2,742
  • 2
  • 23
  • 41
Varun Jain
  • 1,901
  • 7
  • 33
  • 66

3 Answers3

27

I work with sessions under Yii in another way, I use the global session variable under the app() variable. So you can store values like this:

Yii::app()->session['sleep'] = "value";

And you can get values like this:

$sleep = Yii::app()->session['sleep'];

Finally you can remove it like this:

unset(Yii::app()->session['sleep']);

This way you can access them everywhere in your code. I recommend you to read this article: http://www.larryullman.com/2011/05/03/using-sessions-with-the-yii-framework/ it has all the information that you need.

Skatox
  • 4,237
  • 12
  • 42
  • 47
  • Yeah , this is what I ended up doing !! Thanks for the answer anyways !! – Varun Jain Nov 24 '12 at 22:49
  • I Use it too. But, what's difference between this and CHttpSession? – shgnInc Dec 11 '13 at 07:42
  • I think the only difference is that CHttpsession lets you control when to open or close the session and uses object oriented approach, the other way uses Yii's states. – Skatox Dec 12 '13 at 00:50
  • However, accessing them "everywhere in your code" means "everywhere" is coupled to the global session. Session access should be minimized and centralized. – grantwparks Nov 11 '14 at 16:04
3

To remove the session variable in yii...

Please use this actual format.

Yii::app()->session->remove('session_name');

http://www.yiiframework.com/doc/api/1.1/CHttpSession#remove-detail

Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
Akhil K R
  • 31
  • 2
-1
$session = new \yii\web\Session();

$session->open(); 

$session['account_id'] = $id; 

$session['account_name'] = $name;
Jitendra Y
  • 25
  • 11
  • 1
    code only answers are aweful. Please add some explanation on why/how this works. This is yii2 by the way, not directly related to OP's issue. – Gogol Jul 22 '16 at 07:10