CakePHP 2 “remember me” feature

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.

Depending on how your login function is implemented the code above should be used in a similar manner:

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:

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’).

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:

TIP: Remember to load the Cookies component in you AppController as follows: