So I am going to show how to implement a “remember me” feature in CakePHP 2 while utilizing Cake’s Auth.
I assume that you already have a working installation of CakePHP 2 and that the controller which you are using for authentication is called: User. Also, that your username and password fields in the ‘users’ table are called respectively ‘username’ and ‘password’( this should be the case if you want Auth to handle things automatically for you ). If you don’t have Auth configured and working you can go here and follow the instructions there.
So firstly, add the following code to your login form view. This is just using CakePHP form helper to output the “remember me” checkbox and a label. You can style it however you like.
<?php echo $this->Form->input('rememberMe', array('type' => 'checkbox', 'label' => 'Remember me')); ?>
Depending on how your login function is implemented the code above should be used in a similar manner:
if ($this->Auth->login()) {
// The previous piece of code goes here
$this->redirect('/users/profile');
}
Next, add the following code in the beforeFilter() method of your AppController class( which resides in app/controller/AppController.php ) so it should look like the following:
class AppController extends Controller {
// Our code follows from here
public function beforeFilter() {
// set cookie options
$this->Cookie->httpOnly = true;
if (!$this->Auth->loggedIn() && $this->Cookie->read('rememberMe')) {
$cookie = $this->Cookie->read('rememberMe');
$this->loadModel('User'); // If the User model is not loaded already
$user = $this->User->find('first', array(
'conditions' => array(
'User.username' => $cookie['username'],
'User.password' => $cookie['password']
)
));
if ($user && !$this->Auth->login($user['User'])) {
$this->redirect('/users/logout'); // destroy session & cookie
}
}
// The rest of AppController goes here
}
Updating the logout function accordingly. Add this to any controller which you want to handle the logout poccess. Note the use of $this->Cookie->delete(‘rememberMe’).
public function logout() {
$this->Session->setFlash("You've been logged out");
$this->Cookie->delete('rememberMe');
$this->redirect($this->Auth->logout());
}
That’s it. You can go ahead and test it now. Note that I’ve tested this on CakePHP 2.2.5 but it should work on anything upwards of 2.0(inclusive)
TIP: When creating new controllers and you are overriding the beforeFilter() method you should add the following code at the beginning of your beforeFilter() method. This ensures that the last piece of code always gets executed:
parent::beforeFilter();
TIP: Remember to load the Cookies component in you AppController as follows:
public $components = array(
‘Cookie’
// Load other components
);