2
votes

I am very new to CakePHP and the whole MVC framework. My question is where is the best place to incorporate sessions in my website.

I want to start a session as soon as a user visits the site and check if it is valid and if the user is logged in (via a session attribute) before each call to a controller.

Should I be placing the logic to check for a valid session in the AppController? if so how can I do that because nothing instantiates the AppController so I cannot use $this->html->session().

Many Thanks

2
Sessions are form of storage, which should give you quite a good idea where and how they should be used. - tereško
The AuthComponent will most probably handle all your requirements by default. - user221931

2 Answers

1
votes

You are on the right track, but take another look at the documentation on Sessions.

You want to be using $this->Session->read/write/check/etc

Cakephp will always start a session if you've included the Session component and for the most part this is exactly what you want. In the AppController you only need to tell CakePHP to use the Session component.

Something like this...

 public $components = array(
        'Session',
        'RequestHandler',
        'Cookie'
    );

And then include the helper as well...

  public $helpers = array('Html', 'Form', 'Session');

Now you're ready to rock.

0
votes

To store a value in the session :

  $this->Session->write("myvalue");

to read a value from the session:

$this->Session->read("myvalue");

You can also check if a value is set using :

$this->Session->check("myvalue");

You can also use beforeFilters in your controller to block access to the controller:

public function beforeFilter(){
   parent::beforeFilter();
   if(!$this->Session->check("id")){
      $this->redirect("/users/login");
}
}

Alternatively just wrap the above in a private method and call the method on the first line of all the actions you want to control access to.