CakePHP 2.x Login System


Well, since one of my most popular all-time blog posts is Login system with CakePHP in under 10 minutes I think it’s time that I update it to version 2.x (currently 2.2 at the time of writing).  The original post was probably written for version 1.2 or 1.1 and there have been several changes made, especially with breaking changes to the AuthenicateComponent.

The beautiful part is the changes are extremely limited.  In fact, only the UsersController requires a few minor changes.

 In case you haven’t read the previous post, I’ll walk through the entire process.  Firstly we need a database table to store the users:

`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
KEY `email` (`email`)

Once the users table is created in your database, a model is required as well.  Create a new file called UserModel.php inside of your app/Model directory:

class UserModel extends AppModel {

Next a controller is required to display and execute the login process.  Create a new file called UsersController.php inside of your app/Controller directory:

App::uses(‘AppController’, ‘Controller’);

class UsersController extends AppController {

public $name = ‘Users’;
public $uses = array(‘User’);

// Pass settings in $components array
public $components = array(
‘Auth’ => array(
‘loginAction’ => array(
‘controller’ => ‘users’,
‘action’ => ‘login’,
‘authError’ => ‘Did you really think you are allowed to see that?’,
‘authenticate’ => array(‘Form’)

public function login() {
if ($this->request->is(‘post’)) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__(‘Username or password is incorrect’), ‘default’, array(), ‘auth’);

public function logout() {
return $this->redirect($this->Auth->logout());

And finally a view is required to display the login form.  Create a new file called login.ctp and place it inside of your app/View/Users folder:

echo $this->Session->flash(‘auth’);
echo $this->Form->create(‘User’);
echo $this->Form->input(‘username’);
echo $this->Form->input(‘password’);
echo $this->Form->end(‘Login’);

That’s it!  90% of this code is completely the same as the original CakePHP login post, makes it nice and easy to stay on top of the new updates!

Other useful articles

About the author

  • himanshu

    class UserModel extends AppModel it should be class User extend

  • Guest


  • Guest

    There is database error

By Jamie

My Books