Hello, dude. How are you doing? This tutorial will be on a login and registration system with CakePHP. Actually, I have planned to create a personal blog with login and registration facility. I think, this way it will be more useful of your learning. As, I took a pretty big break of writing on CakePHP, this article will be little big compare to other tutorials of CakePHP. Ready now?
Before start, you should read the other CakePHP tutorials first. Then come to it. Otherwise it would be painful to you. Because, I am not going to explain all the codes, line by line. Most of the codes you will know if you complete previous tutorials. Ohh.. one more thing we will think about fancy css style. We will use default css style given by CakePHP. So, take a deep breath.
First is first, go to CakePHP website and download the latest version of it. Extract it, inside the your htdocs folder and rename as “logreg”. Now open this folder with your IDE and start coding.
Step1:
Let’s create our database. We will have two tables called posts and users. Post table contains all of your posts and the user table contains your user information including your encrypted password.
-- -- Database: `logregcake` -- CREATE DATABASE `logregcake`; USE `logregcake`; -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE IF NOT EXISTS `posts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(50) DEFAULT NULL, `body` text, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `email` varchar(50) NOT NULL, `phone` varchar(50) DEFAULT NULL, `role` varchar(20) DEFAULT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
Step 2:
Rename database.php.default to database.php from config folder and give your database credentials,
public $default = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => 'logregcake', 'prefix' => '', //'encoding' => 'utf8', );
Now open core.php from the same folder and rewrite the your salt info, about at lines 225 and 230 –
/** * A random string used in security hashing methods. */ Configure::write('Security.salt', 'ShahjalalHossain'); /** * A random numeric string (digits only) used to encrypt/decrypt strings. */ Configure::write('Security.cipherSeed', 'ShahjalalHossain');
Step 3:
Let’s create our model first. As we have two tables in our database, so we will need two Models.
Create Post.php in the Model folder and write your model –
App::uses('AppModel', 'Model'); /** * Post Model * */ class Post extends AppModel { public function isOwnedBy($post, $user) { return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false; } }
Now create User.php in the same folder and create the corresponding model –
App::uses('AppModel', 'Model'); App::uses('SimplePasswordHasher', 'Controller/Component/Auth'); /** * User Model * */ class User extends AppModel { public $validate = array( 'username' => array( 'required' => array( 'rule' => array('notEmpty'), 'message' => 'A username is required' ) ), 'password' => array( 'required' => array( 'rule' => array('notEmpty'), 'message' => 'A password is required' ) ), 'email' => array( 'email' => array( 'rule' => array('email', true), 'message' => 'Please supply a valid email address.' ), 'required' => array( 'rule' => array('notEmpty'), 'message' => 'A email is required' ) ), 'role' => array( 'valid' => array( 'rule' => array('inList', array('admin', 'author')), 'message' => 'Please enter a valid role', 'allowEmpty' => false ) ) ); public function beforeSave($options = array()) { if (isset($this->data[$this->alias]['password'])) { $passwordHasher = new SimplePasswordHasher(); $this->data[$this->alias]['password'] = $passwordHasher->hash( $this->data[$this->alias]['password'] ); } return true; } }
In the user model we have set some form validation code and in the beforeSave() method we have encrypt our password.
Step 4:
We are done with our Model, so we need to create our Controller, now.
App::uses('AppController', 'Controller'); /** * Posts Controller * * @property Post $Post * @property PaginatorComponent $Paginator */ class PostsController extends AppController { /** * Components * * @var array */ public $components = array('Paginator'); /** * index method * * @return void */ public function index() { $this->Post->recursive = 0; $this->set('posts', $this->Paginator->paginate()); } public function visitors(){ $this->Post->recursive = 0; $this->set('posts', $this->Paginator->paginate()); } /** * view method * * @throws NotFoundException * @param string $id * @return void */ public function view($id = null) { if (!$this->Post->exists($id)) { throw new NotFoundException(__('Invalid post')); } $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id)); $this->set('post', $this->Post->find('first', $options)); } /** * add method * * @return void */ public function add() { if ($this->request->is('post')) { $this->Post->create(); if ($this->Post->save($this->request->data)) { $this->Session->setFlash(__('The post has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The post could not be saved. Please, try again.')); } } } /** * edit method * * @throws NotFoundException * @param string $id * @return void */ public function edit($id = null) { if (!$this->Post->exists($id)) { throw new NotFoundException(__('Invalid post')); } if ($this->request->is(array('post', 'put'))) { if ($this->Post->save($this->request->data)) { $this->Session->setFlash(__('The post has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The post could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id)); $this->request->data = $this->Post->find('first', $options); } } /** * delete method * * @throws NotFoundException * @param string $id * @return void */ public function delete($id = null) { $this->Post->id = $id; if (!$this->Post->exists()) { throw new NotFoundException(__('Invalid post')); } $this->request->allowMethod('post', 'delete'); if ($this->Post->delete()) { $this->Session->setFlash(__('The post has been deleted.')); } else { $this->Session->setFlash(__('The post could not be deleted. Please, try again.')); } return $this->redirect(array('action' => 'index')); } }
Each method in this folder is call their corresponding ctp file from the view.
Now, create UsersController.php in the same folder –
App::uses('AppController', 'Controller'); /** * Users Controller * * @property User $User * @property PaginatorComponent $Paginator */ class UsersController extends AppController { /** * Components * * @var array */ public $components = array('Paginator'); public function beforeFilter() { parent::beforeFilter(); $this->Auth->allow('add', 'logout'); } /** * index method * * @return void */ public function index() { $this->User->recursive = 0; $this->set('users', $this->Paginator->paginate()); } /** * view method * * @throws NotFoundException * @param string $id * @return void */ public function view($id = null) { if (!$this->User->exists($id)) { throw new NotFoundException(__('Invalid user')); } $options = array('conditions' => array('User.' . $this->User->primaryKey => $id)); $this->set('user', $this->User->find('first', $options)); } /** * add method * * @return void */ public function add() { if ($this->request->is('post')) { $this->User->create(); if ($this->User->save($this->request->data)) { $this->Session->setFlash(__('The user has been saved.')); return $this->redirect(array('controller' => 'Posts', 'action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.')); } } } /** * edit method * * @throws NotFoundException * @param string $id * @return void */ public function edit($id = null) { if (!$this->User->exists($id)) { throw new NotFoundException(__('Invalid user')); } if ($this->request->is(array('post', 'put'))) { if ($this->User->save($this->request->data)) { $this->Session->setFlash(__('The user has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('User.' . $this->User->primaryKey => $id)); $this->request->data = $this->User->find('first', $options); } } /** * delete method * * @throws NotFoundException * @param string $id * @return void */ public function delete($id = null) { $this->User->id = $id; if (!$this->User->exists()) { throw new NotFoundException(__('Invalid user')); } $this->request->allowMethod('post', 'delete'); if ($this->User->delete()) { $this->Session->setFlash(__('The user has been deleted.')); } else { $this->Session->setFlash(__('The user could not be deleted. Please, try again.')); } return $this->redirect(array('action' => 'index')); } public function login() { if ($this->request->is('post')) { if ($this->Auth->login()) { return $this->redirect($this->Auth->redirect(array('controller' => 'Posts', 'action' => 'index'))); } $this->Session->setFlash(__('Invalid username or password, try again')); } } public function logout() { //return $this->redirect($this->Auth->logout()); return $this->redirect($this->Auth->logout($this->Auth->redirect(array('controller' => 'Posts', 'action' => 'visitors')))); } }
Now open the AppController.php and add some code for our page redirection and authentication.
App::uses('Controller', 'Controller'); class AppController extends Controller { public $components = array( 'Session', 'Auth' => array( 'loginRedirect' => array( 'controller' => 'posts', 'action' => 'index' ), 'logoutRedirect' => array( 'controller' => 'posts', 'action' => 'visitors' ) ) ); public function beforeFilter() { $this->Auth->allow('index', 'view', 'visitors'); } public function isAuthorized($user) { if ($this->action === 'add') { return true; } if (in_array($this->action, array('edit', 'delete'))) { $postId = (int) $this->request->params['pass'][0]; if ($this->Post->isOwnedBy($postId, $user['id'])) { return true; } } return parent::isAuthorized($user); } }
Step 5:
We are going to create all of our views in View folder. In this create two folder called Posts and Users.
Let’s work with our posts, first. Inside Posts folder create –
index.ctp
<div class="posts index"> <h2><?php echo __('Posts'); ?></h2> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th><?php echo $this->Paginator->sort('id'); ?></th> <th><?php echo $this->Paginator->sort('title'); ?></th> <th><?php echo $this->Paginator->sort('body'); ?></th> <th><?php echo $this->Paginator->sort('created'); ?></th> <th><?php echo $this->Paginator->sort('modified'); ?></th> <th class="actions"><?php echo __('Actions'); ?></th> </tr> </thead> <tbody> <?php foreach ($posts as $post): ?> <tr> <td><?php echo h($post['Post']['id']); ?> </td> <td><?php echo h($post['Post']['title']); ?> </td> <td><?php echo h($post['Post']['body']); ?> </td> <td><?php echo h($post['Post']['created']); ?> </td> <td><?php echo h($post['Post']['modified']); ?> </td> <td class="actions"> <?php echo $this->Html->link(__('View'), array('action' => 'view', $post['Post']['id'])); ?> <?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $post['Post']['id'])); ?> <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $post['Post']['id']), array(), __('Are you sure you want to delete # %s?', $post['Post']['id'])); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <p> <?php echo $this->Paginator->counter(array( 'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}') )); ?> </p> <div class="paging"> <?php echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled')); echo $this->Paginator->numbers(array('separator' => '')); echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled')); ?> </div> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('New Post'), array('action' => 'add')); ?></li> <li><?php echo $this->Html->link(__('Logout'), array('controller' => 'Users', 'action' => 'logout')); ?></li> </ul> </div>
add.ctp
<div class="posts form"> <?php echo $this->Form->create('Post'); ?> <fieldset> <legend><?php echo __('Add Post'); ?></legend> <?php echo $this->Form->input('title'); echo $this->Form->input('body'); ?> </fieldset> <?php echo $this->Form->end(__('Submit')); ?> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('List Posts'), array('action' => 'index')); ?></li> <li><?php echo $this->Html->link(__('Logout'), array('controller' => 'Users', 'action' => 'logout')); ?></li> </ul> </div>
Create edit.ctp in same folder
<div class="posts form"> <?php echo $this->Form->create('Post'); ?> <fieldset> <legend><?php echo __('Edit Post'); ?></legend> <?php echo $this->Form->input('id'); echo $this->Form->input('title'); echo $this->Form->input('body'); ?> </fieldset> <?php echo $this->Form->end(__('Submit')); ?> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('Post.id')), array(), __('Are you sure you want to delete # %s?', $this->Form->value('Post.id'))); ?></li> <li><?php echo $this->Html->link(__('List Posts'), array('action' => 'index')); ?></li> <li><?php echo $this->Html->link(__('Logout'), array('controller' => 'Users', 'action' => 'logout')); ?></li> </ul> </div>
view.ctp
<div class="posts view"> <h2><?php echo __('Post'); ?></h2> <dl> <dt><?php echo __('Id'); ?></dt> <dd> <?php echo h($post['Post']['id']); ?> </dd> <dt><?php echo __('Title'); ?></dt> <dd> <?php echo h($post['Post']['title']); ?> </dd> <dt><?php echo __('Body'); ?></dt> <dd> <?php echo h($post['Post']['body']); ?> </dd> <dt><?php echo __('Created'); ?></dt> <dd> <?php echo h($post['Post']['created']); ?> </dd> <dt><?php echo __('Modified'); ?></dt> <dd> <?php echo h($post['Post']['modified']); ?> </dd> </dl> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Post'), array('action' => 'edit', $post['Post']['id'])); ?> </li> <li><?php echo $this->Form->postLink(__('Delete Post'), array('action' => 'delete', $post['Post']['id']), array(), __('Are you sure you want to delete # %s?', $post['Post']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Posts'), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Post'), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('Logout'), array('controller' => 'Users', 'action' => 'logout')); ?></li> </ul> </div>
visitors.ctp
<div class="posts index"> <h2><?php echo __('Posts'); ?></h2> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th><?php echo $this->Paginator->sort('id'); ?></th> <th><?php echo $this->Paginator->sort('title'); ?></th> <th><?php echo $this->Paginator->sort('body'); ?></th> <th><?php echo $this->Paginator->sort('created'); ?></th> <th><?php echo $this->Paginator->sort('modified'); ?></th> </tr> </thead> <tbody> <?php foreach ($posts as $post): ?> <tr> <td><?php echo h($post['Post']['id']); ?> </td> <td><?php echo h($post['Post']['title']); ?> </td> <td><?php echo h($post['Post']['body']); ?> </td> <td><?php echo h($post['Post']['created']); ?> </td> <td><?php echo h($post['Post']['modified']); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <p> <?php echo $this->Paginator->counter(array( 'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}') )); ?> </p> <div class="paging"> <?php echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled')); echo $this->Paginator->numbers(array('separator' => '')); echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled')); ?> </div> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Login'), array('controller' => 'Users', 'action' => 'login')); ?></li> </ul> </div>
We are done with our posts, so now let’s work with our users. Inside Users folder create –
index.ctp
<div class="users index"> <h2><?php echo __('Users'); ?></h2> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th><?php echo $this->Paginator->sort('id'); ?></th> <th><?php echo $this->Paginator->sort('username'); ?></th> <th><?php echo $this->Paginator->sort('password'); ?></th> <th><?php echo $this->Paginator->sort('role'); ?></th> <th><?php echo $this->Paginator->sort('created'); ?></th> <th><?php echo $this->Paginator->sort('modified'); ?></th> <th class="actions"><?php echo __('Actions'); ?></th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?php echo h($user['User']['id']); ?> </td> <td><?php echo h($user['User']['username']); ?> </td> <td><?php echo h($user['User']['password']); ?> </td> <td><?php echo h($user['User']['role']); ?> </td> <td><?php echo h($user['User']['created']); ?> </td> <td><?php echo h($user['User']['modified']); ?> </td> <td class="actions"> <?php echo $this->Html->link(__('View'), array('action' => 'view', $user['User']['id'])); ?> <?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $user['User']['id'])); ?> <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $user['User']['id']), array(), __('Are you sure you want to delete # %s?', $user['User']['id'])); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <p> <?php echo $this->Paginator->counter(array( 'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}') )); ?> </p> <div class="paging"> <?php echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled')); echo $this->Paginator->numbers(array('separator' => '')); echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled')); ?> </div> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('New User'), array('action' => 'add')); ?></li> </ul> </div>
add.ctp
<div class="users form"> <?php echo $this->Form->create('User'); ?> <fieldset> <legend><?php echo __('Add User'); ?></legend> <?php echo $this->Form->input('username'); echo $this->Form->input('password'); echo $this->Form->input('email'); echo $this->Form->input('phone'); echo $this->Form->input('role', array('type'=>'hidden', 'value'=>'admin')); ?> </fieldset> <?php echo $this->Form->end(__('Submit')); ?> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li>Register your details.</li> </ul> </div>
edit.ctp
<div class="users form"> <?php echo $this->Form->create('User'); ?> <fieldset> <legend><?php echo __('Edit User'); ?></legend> <?php echo $this->Form->input('id'); echo $this->Form->input('username'); echo $this->Form->input('password'); echo $this->Form->input('role'); ?> </fieldset> <?php echo $this->Form->end(__('Submit')); ?> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $this->Form->value('User.id')), array(), __('Are you sure you want to delete # %s?', $this->Form->value('User.id'))); ?></li> <li><?php echo $this->Html->link(__('List Users'), array('action' => 'index')); ?></li> </ul> </div>
login.ctp
<div class="users form"> <?php echo $this->Session->flash('auth'); ?> <?php echo $this->Form->create('User'); ?> <fieldset> <legend> <?php echo __('Please enter your username and password'); ?> </legend> <?php echo $this->Form->input('username'); echo $this->Form->input('password'); ?> </fieldset> <?php echo $this->Form->end(__('Login')); ?> or, <?php echo $this->Html->link(__('Register'), array('action' => 'add')); ?> </div>
view.ctp
<div class="users view"> <h2><?php echo __('User'); ?></h2> <dl> <dt><?php echo __('Id'); ?></dt> <dd> <?php echo h($user['User']['id']); ?> </dd> <dt><?php echo __('Username'); ?></dt> <dd> <?php echo h($user['User']['username']); ?> </dd> <dt><?php echo __('Password'); ?></dt> <dd> <?php echo h($user['User']['password']); ?> </dd> <dt><?php echo __('Role'); ?></dt> <dd> <?php echo h($user['User']['role']); ?> </dd> <dt><?php echo __('Created'); ?></dt> <dd> <?php echo h($user['User']['created']); ?> </dd> <dt><?php echo __('Modified'); ?></dt> <dd> <?php echo h($user['User']['modified']); ?> </dd> </dl> </div> <div class="actions"> <h3><?php echo __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit User'), array('action' => 'edit', $user['User']['id'])); ?> </li> <li><?php echo $this->Form->postLink(__('Delete User'), array('action' => 'delete', $user['User']['id']), array(), __('Are you sure you want to delete # %s?', $user['User']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Users'), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User'), array('action' => 'add')); ?> </li> </ul> </div>
Ohh.. I almost forgot. Open routes.php from config folder and create some changes in the following lines to set our default routes
Router::connect('/', array('controller' => 'posts', 'action' => 'visitors')); /** * ...and connect the rest of 'Pages' controller's URLs. */ Router::connect('/logreg/*', array('controller' => 'posts', 'action' => 'visitors'));
Done… Done… Done…
Now open your browser and go to
So you are ready to go and let me know if you have any problem –
Conclusion:
After reading this long post, I think you have pretty good expertise on CakePHP. You can start thinking yourself as a CakePHP professional.
Happy Coding … 🙂
Login and Registration System with CakePHP
Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.
Please send the code for user login page,user registration , edit user, delete user, find user detail from user database table in cake php 3.2or cakephp 3.0 with code……i have urgen require..so please send me iiion my gmail:- mandeepkhaleriya.08@gmail.com
testttt
delete post generate “Method allowMethod does not exist”
Hello, I think your website might be having browser compatibility issues. When I look at your website in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, awesome blog!
One of the best explanation i experienced.
It’s a pity you don’t have a donate button! I’d certainly donate to this excellent blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this site with my Facebook group. Chat soon!
please send me admin login and logout detail code in cake php 3 and 3.2.
please send me admin login and logout code in cake php3 and cake php 3.2 in obmsppdas21@gmail.com
Awesome things here. I’m very satisfied to peer your post. Thanks so much and I am looking ahead to touch you. Will you kindly drop me a e-mail?
I copied the same code. But I am getting the error “syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file”