CakePHP: Session->write() not working

心不动则不痛 提交于 2019-12-11 09:57:12

问题


I'm building a very basic auth system for specific pages which require a password to view. I've found several other questions that sound similar, but the only ones with clear solutions involve config settings that don't seem to resolve my problem. For some reason $this->Session->write(...) always returns false.

Here's my config setting:

Configure::write('Session', array(
    'defaults' => 'php'
));

Here's where I try to write the session in the controller action:

private function _handle_auth_attempt( $object ) {
    $submitted_pass = $this->request->data['Object']['password'];
    $correct_pass = $object['Object']['password'];
    $auth_cookie_name = $this->Object->auth_cookie_name($object);

    debug($auth_cookie_name); //'Object1.pass'
    debug($submitted_pass); //'foobar'

    if ( md5($submitted_pass) == md5($correct_pass) ) {
        $write1 = $this->Session->write( $auth_cookie_name, md5($submitted_pass) );
        $write2 = CakeSession::write( $auth_cookie_name, md5($submitted_pass) );            
        debug($write1); //FALSE
        debug($write2); //FALSE
        return TRUE;
    }

    $this->Session->setFlash('The password you entered is incorrect.');
    $this->redirect( $this->referer() );

}

Update

Inside _handle_auth_attempt() I added:

$_SESSION['foo'] = 'bar';
$this->Session-read('foo'); //'bar'

...and they work fine. So I'm pretty sure this isn't a permissions problem.


回答1:


From the source code, one possibilities of FALSE is that the session name is empty. So can you check what result is

debug($auth_cookie_name);



回答2:


I don't understand this at all, but I removed the "." from inside my session cookie's name and it causes Session->write() to work again.

$this->Session->write('Object1.pass'); //FALSE
$this->Session->write('Object1pass'); //TRUE

Although this solves my immediate problem, I'd love to understand this problem better.

Update

After thinking this through more, I suspect that what was happening is a combination of factors:

  1. CakePHP uses the "dot" notation to store session inside arrays which I wasn't accounting for.
  2. The very first time I ran the code, it probably worked...
  3. But every subsequent attempt it returned FALSE because it already existed <--untested
  4. I have no explanation why read() was returning false.



回答3:


All your session read/writes belong in the controller:

$this->Session->write('User.still_login', 'Yes');

echo $this->Session->read('User.still_login'); // Yes as output


来源:https://stackoverflow.com/questions/20530305/cakephp-session-write-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!