Login system with CakePHP in under 10 minutes

** 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.

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.

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.

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:

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.