Login system with CakePHP in under 10 minutes

L

** If you’ve found this article through a Google search, visit my CakePHP 2.x Login System for an updated version of this article. **

In today’s article, I am going to discuss how simple it is to setup a login system with CakePHP.  As the title says, it should be less than 10 minutes.  In theory if you copy and paste the code below, it should be fully functional in less than 5.

Ready, set, let’s bake.

Step 1, create a users table:

[code]CREATE TABLE  `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`created` datetime default NULL,
`modified` datetime default NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
[/code]

The above is a very basic users table.  We will be using an email address for the login instead of a username.  We’ll do this to demonstrate more features of the Auth setup in CakePHP.

Step 2, update your users_controller.php:

[code]/**
*  The AuthComponent provides the needed functionality
*  for login, so you can leave this function blank.
*/
function login() {}

function logout() {
$this->redirect($this->Auth->logout());
}
[/code]

The above is just a snippet of our users controller.  As you can see, we create a blank login function because CakePHP takes care of everything for us.  Our logout function, logs us out and redirects back to the login page that we will specify shortly.

Step 3, create app/views/users/login.ctp:

[code]<?php
if  ($session->check(‘Message.auth’)) $session->flash(‘auth’);
echo $form->create(‘User’, array(‘action’ => ‘login’));
echo $form->input(’email’);
echo $form->input(‘password’);
echo $form->end(‘Login’);
?>
[/code]

This code creates a basic form with email address and password.  If an auth message exists, it will be displayed above the form.  This is usually where our error messages are displayed about invalid login or access denied, etc…

Step 4, this step can be completed in an individual controller if you only require security in one controller, however, if you need it on multiple controllers, I would suggest adding this to your app_controller.php.

[code]class AppController extends Controller {

var $components = array(‘Auth’);

function beforeFilter() {
$this->Auth->userModel = ‘User’;
$this->Auth->fields = array(‘username’ => ’email’, ‘password’ => ‘password’);
$this->Auth->loginAction = array(‘admin’ => false, ‘controller’ => ‘users’, ‘action’ => ‘login’);
$this->Auth->loginRedirect = array(‘controller’ => ‘users’, ‘action’ => ‘index’);
}

}
[/code]

As it always seems to be with CakePHP, the above contains some more simple code.  We start by including the Auth Component.  Then in our beforeFilter() function we tell CakePHP how to configure our security.  The first line tells Cake to use the User model.  Next, we configure it to use email and password as the fields oppose to the default of username and password.  It’s important to note, if you wish to change only one of the fields, you are still required to update both.  Next we tell CakePHP to redirect to the users controller and the login function when we are not logged in.  Finally, we tell CakePHP when we have successfully logged in to redirect to the index function of our users controller.

A couple of things to note, we do not specify any allow() pages.  This means that by default ALL of our functions require authorization.

Because we’ve specified the above in our app_controller, we can easily override the defaults on individual controllers for more flexibility.  For example, here is a snippet of code from a users_controller.php that allows the add function, because we want people to be able to register without logging in:

[code]function beforeFilter() {
$this->Auth->allow(‘add’);
parent::beforeFilter();
}
[/code]

The above code, tells CakePHP to allow the add function in our users_controller.php.  Then it calls the parent beforeFilter function to setup the remaining Auth code.

That’s it, authorization is setup.  I remember feeling overwhelmed by creating a login script with Auth when I first started.  It wasn’t until I tried it that I realized how easy it was, hopefully you will feel the same way now.

About the author

  • qwant

    I run into a problem at step 2: I don’t have a users_controller.php file in my cakephp directory. Any suggestions?

  • qgive
  • http://blog.juliendesrosiers.com Julien

    big time saver, thanks a lot for this little tutorial!

    J.

  • Frederick D.

    Thanks very much for the clear article. I have implemented this successfully. Would you do me a favor please? Would you advise me on some sample code to display the user name after a successful login?

    This is what I’ve tried in my users_controller.php file:

    function login() {
    $this->Session->setFlash(‘Please enter your Username and Password.’);
    if ($this->Auth->user()) {
    $this->Session->setFlash(‘You are now logged in.’);
    }
    }

    I get the message “Please enter…” when the login.ctp file is rendered, but I do not get the message on the way out. What am I doing wrong? Plus, I would like the userid in the success message.

    Thanks in advance!

  • http://webarya.wordpress.com/ Aryashree Pritikrishna

    Thanks a lot for the code. Its working perfectly.

    Cheers,
    Arya

  • http://www.wotlkgold.net wow gold

    Looks like your question thing at the end of the post worked. Also not having to sign in is nice too. Good job. Nice list. Thanks.

  • http://www.boffinsbook.com/ abroadstudent

    Hey,,,
    you need to specify which link user will click to get to the login/registration pages

  • Kevin

    Nice article! But, there shouldn’t be any logic in your view. 😉

  • Kevin

    Well, I won’t say there shouldn’t be any logic, but ya might as well keep it in your controller if you can. 😛

  • distro

    Hello guys i am newbie of cakephp… i followed what you say in your post.. by my code was not running what i want…

    this is trhe scenario when i click the submit button it will not says anything……. how can i put a word that says’ “Your welcome visitors” when the email and password are correc …. And “Invalid email/password” if the email and password was incorrect.

    my table users(id,email,lastname,age,address,password username)

    file /blog/app/views/users/login.ctp

    Login form
    check(‘Message.Auth’)) $session->flash(‘auth’);

    echo $form->create(‘User’,array(‘action’ => ‘login’));
    echo $form->input(’email’);
    echo $form->input(‘password’,array(‘type’ => ‘password’));
    echo $form->submit(‘Login’);
    echo $form->end();
    ?>

    file /blog/cake/libs/controller/app_controller.php

    Auth->userModel = ‘User’;
    $this->Auth->Fields = array(’email’ => ’email’ , ‘password’ => ‘password’);
    $this->Auth->loginAction = array(‘admin’ => ‘false’, ‘controller’ => ‘users’,’action’ => ‘login’);
    $this->Auth->loginRedirect = array(‘controller’ => ‘users’ , ‘action’ => ‘index’);
    }

    }
    ?>

    file /blog/app/controller/users_controller.php

    redirect($this->Auth->logout()) ;
    }

    function index() {
    alot of code……………………………………
    }
    function view($id = null) {
    alot of code……………………………………
    }

    function add() {
    alot of code……………………………………
    }

    function edit($id = null) {
    ………………………………..
    }

    function delete($id = null) {
    alot of code……………………………………
    }

    ?>

    email me [email protected]

  • Cleaned SQL-script

    CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `first_name` varchar(45) NOT NULL,
    `last_name` varchar(45) NOT NULL,
    `email` varchar(45) NOT NULL,
    `password` varchar(45) NOT NULL,
    `created` datetime default NULL,
    `modified` datetime default NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

  • http://[email protected] anderlima

    🙂

  • http://[email protected] anderlima

    😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈 😈

  • http://[email protected] anderlima

    ola :mrgreen: :mrgreen:

  • Cesar Pineda

    Hello:

    I’m beginning to work with cakephp and I have a little question. I copied-pasted the code but it isn’t working. When I clic on submit button, the page redirects to login again, and I can’t do anything. Do I have to hash the password of my users table? Or maybe I have to do anything else that I’m missing.
    Thank you in advance.

  • Mischa

    I have the same problem with Cesar Pineda.

    Hope u can advice accordingly.

    Thanks.

  • http://www.iamceo.in Kiran Ambati

    @Cesar Pineda , @Mischa Just hash password before saving user details through registration form. That worked for me.

    Thanks

  • http://www.danielhanly.com Daniel Hanly

    Thank you Jamie, you are a lifesaver. In the cake book they only have the ability to do this with Acl. I’m building my website and I’m the only administrative person who needs to access it. I don’t need Access Control Lists or user groups etc.

    Your code is ideal. Thank you.

  • Cesar Pineda

    @Kiran Ambati That was the problem. Thank you for the answer. It really worked!!!.
    @Mischa When you get to the AppController, just add the line $this->Auth->allow(‘*’); in the beforeFilter method. Then add an User as you were logged in in your own app. When you’ve added succesfully your user, then remove the line $this->Auth->allow(‘*’); writen before. Then try to add it again. You won’t be able, because the login() is working now.
    The real problem is that the comparison between the password we had before and with the login() method is that login() method is hashing the parameter. So, with the allow(*) line, the add of the user, Cake is Hashing the password for you.
    Hope it helps

  • Pingback: Fantasy Football Faux Paux » Blog Archive » Harbaugh: 49ers will ‘kick the tires’ on veteran Culpepper

  • Pingback: SZI Outsourcing Client Business Relationship ? The Business … | Space News Articles

  • Pingback: How to remove skin tags

  • Pingback: secrets 4 loss weight

  • Pingback: remote virus help

  • Pingback: Goozle Zone

  • Pingback: Ania Antonette Quisumbing

  • Pingback: bad credit loans

  • Pingback: guayabera san antonio

  • Pingback: top songs download website

  • Pingback: one buck resume

  • Pingback: End Your If CakePHP 2.x Login System | End Your If

  • Pingback: payday loans online

  • Pingback: ultimate power profits

By Jamie

My Books