Registration and Login is one of the primary module in any data management system. In this tutorial, we will explain how to create user Registration authentication and user Login system using the CodeIgniter. Using
Step 1: Create Database
For this tutorial, you need a MySQL database with the following table:
Step 2: Configure Database access
Update the file
Step 3: Update routes file
Add code the file
Step 4: Update autoload file
In the file
Step 5: Create Model
Create a model file named
Step 6: Create controllers
Create a controllers file named
Step 7: Create mailing class with
Create a model file named
Step 8: Create views for registration
Create a views file named
Step 9: Create views for login
Create a views file named
Step 10: Create views for Forgot Password
Create a views file named
Step 11: Create views for profile page
Create a views file named
Step 12: Create views for edit profile page
Create a views file named
Step 13: Create views for change password page
Create a views file named
Demo [sociallocker] Download[/sociallocker]
password_hash()
and password_verify()
algorithm.Features of Registration and Login Module
- Registration form
- Login form
- Forgot password
- Logout feature
- password_hash() algorithm
- password_verify() algorithm
- Change Password feature
- Email authentication for registration process
- Using SMTP (Simple Mail Transfer Protocol)
- Forms validations on login and registration panel
- On success the module redirects to the user profile page
Step 1: Create Database
For this tutorial, you need a MySQL database with the following table:
//Table structure for table import
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
`first_name` varchar(100) NOT NULL COMMENT 'First Name',
`last_name` varchar(100) NOT NULL COMMENT 'Last Name',
`user_name` varchar(100) NOT NULL COMMENT 'Last Name',
`email` varchar(255) NOT NULL COMMENT 'Email Address',
`contact_no` VARCHAR(16) NOT NULL COMMENT 'Contact No',
`password` varchar(255) NOT NULL COMMENT 'Password',
`address` TEXT NOT NULL COMMENT 'Address',
`dob` varchar(15) NOT NULL COMMENT 'Date Of Birth',
`verification_code` varchar(255) NOT NULL COMMENT 'verification Code',
`created_date` varchar(12) NOT NULL COMMENT 'created timestamp',
`modified_date` varchar(12) NOT NULL COMMENT 'modified timestamp',
`status` char(1) NOT NULL COMMENT '0=pending, 1=active, 2=delete',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
?>
Step 2: Configure Database access
Update the file
application/config/database.php
in your CodeIgniter installation with your database info:
// configure database
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'XXXX', // Your username if required.
'password' => 'XXXX', // Your password if any.
'database' => 'XXXX_DB', // Your database name.
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
?>
Step 3: Update routes file
Add code the file
application/config/routes.php
in your CodeIgniter installation with you controller’s name.
$route['signup'] = 'auth/register';
$route['signin'] = 'auth/login';
$route['profile'] = 'auth/index';
$route['setting'] = 'auth/changepwd';
$route['profile/edit'] = 'auth/edit';
$route['forgotpwd'] = 'auth/forgotpassword';
?>
Step 4: Update autoload file
In the file
application/config/autoload.php
you can configure the default libraries you want to load in all your controllers. For our case, we’ll load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation
// load libraries
$autoload['libraries'] = array('database', 'session', 'table', 'upload');
// load helper
$autoload['helper'] = array('url', 'form', 'html', 'date');
?>
Step 5: Create Model
Create a model file named
Auth_model.php
inside “application/models”
folder.
/* * ***
* Version: V1.0.1
*
* Description of Auth model
*
* @author TechArise Team
*
* @email info@techarise.com
*
* *** */
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Auth_model extends CI_Model {
// Declaration of a variables
private $_userID;
private $_userName;
private $_firstName;
private $_lastName;
private $_email;
private $_password;
private $_contactNo;
private $_address;
private $_dob;
private $_verificationCode;
private $_timeStamp;
private $_status;
//Declaration of a methods
public function setUserID($userID) {
$this->_userID = $userID;
}
public function setUserName($userName) {
$this->_userName = $userName;
}
public function setFirstname($firstName) {
$this->_firstName = $firstName;
}
public function setLastName($lastName) {
$this->_lastName = $lastName;
}
public function setEmail($email) {
$this->_email = $email;
}
public function setContactNo($contactNo) {
$this->_contactNo = $contactNo;
}
public function setPassword($password) {
$this->_password = $password;
}
public function setAddress($address) {
$this->_address = $address;
}
public function setDOB($dob) {
$this->_dob = $dob;
}
public function setVerificationCode($verificationCode) {
$this->_verificationCode = $verificationCode;
}
public function setTimeStamp($timeStamp) {
$this->_timeStamp = $timeStamp;
}
public function setStatus($status) {
$this->_status = $status;
}
//create new user
public function create() {
$hash = $this->hash($this->_password);
$data = array(
'user_name' => $this->_userName,
'first_name' => $this->_firstName,
'last_name' => $this->_lastName,
'email' => $this->_email,
'password' => $hash,
'contact_no' => $this->_contactNo,
'address' => $this->_address,
'dob' => $this->_dob,
'verification_code' => $this->_verificationCode,
'created_date' => $this->_timeStamp,
'modified_date' => $this->_timeStamp,
'status' => $this->_status
);
$this->db->insert('users', $data);
if (!empty($this->db->insert_id()) && $this->db->insert_id() > 0) {
return TRUE;
} else {
return FALSE;
}
}
// login method and password verify
function login() {
$this->db->select('id as user_id, user_name, email, password');
$this->db->from('users');
$this->db->where('email', $this->_userName);
$this->db->where('verification_code', 1);
$this->db->where('status', 1);
//{OR}
$this->db->or_where('user_name', $this->_userName);
$this->db->where('verification_code', 1);
$this->db->where('status', 1);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$result = $query->result();
foreach ($result as $row) {
if ($this->verifyHash($this->_password, $row->password) == TRUE) {
return $result;
} else {
return FALSE;
}
}
} else {
return FALSE;
}
}
//update user
public function update() {
$data = array(
'first_name' => $this->_firstName,
'last_name' => $this->_lastName,
'contact_no' => $this->_contactNo,
'address' => $this->_address,
'dob' => $this->_dob,
'modified_date' => $this->_timeStamp,
);
$this->db->where('id', $this->_userID);
$msg = $this->db->update('users', $data);
if ($msg == 1) {
return TRUE;
} else {
return FALSE;
}
}
//change password
public function changePassword() {
$hash = $this->hash($this->_password);
$data = array(
'password' => $hash,
);
$this->db->where('id', $this->_userID);
$msg = $this->db->update('users', $data);
if ($msg == 1) {
return TRUE;
} else {
return FALSE;
}
}
// get User Detail
public function getUserDetails() {
$this->db->select(array('m.id as user_id', 'CONCAT(m.first_name, " ", m.last_name) as full_name', 'm.first_name', 'm.last_name', 'm.email', 'm.contact_no', 'm.address', 'm.dob'));
$this->db->from('users as m');
$this->db->where('m.id', $this->_userID);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return FALSE;
}
}
// update Forgot Password
public function updateForgotPassword() {
$hash = $this->hash($this->_password);
$data = array(
'password' => $hash,
);
$this->db->where('email', $this->_email);
$msg = $this->db->update('users', $data);
if ($msg > 0) {
return TRUE;
} else {
return FALSE;
}
}
// get Email Address
public function activate() {
$data = array(
'status' => 1,
'verification_code' => 1,
);
$this->db->where('verification_code', $this->_verificationCode);
$msg = $this->db->update('users', $data);
if ($msg == 1) {
return TRUE;
} else {
return FALSE;
}
}
// password hash
public function hash($password) {
$hash = password_hash($password, PASSWORD_DEFAULT);
return $hash;
}
// password verify
public function verifyHash($password, $vpassword) {
if (password_verify($password, $vpassword)) {
return TRUE;
} else {
return FALSE;
}
}
}
?>
Step 6: Create controllers
Create a controllers file named
Auth.php
inside “application/controllers”
folder.
/* * ***
* Version: V1.0.1
*
* Description of Auth Controller
*
* @author TechArise Team
*
* @email info@techarise.com
*
* *** */
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Auth extends MY_Controller {
public function __construct() {
parent::__construct();
//load model
$this->load->model('Auth_model', 'auth');
$this->load->model('Mail', 'mail');
$this->load->library('form_validation');
}
// user profile
public function index() {
if ($this->session->userdata('ci_session_key_generate') == FALSE) {
redirect('signin'); // the user is not logged in, redirect them!
} else {
$data = array();
$data['metaDescription'] = 'User Profile';
$data['metaKeywords'] = 'User Profile';
$data['title'] = "User Profile - TechArise";
$data['breadcrumbs'] = array('Profile' => '#');
$sessionArray = $this->session->userdata('ci_seesion_key');
$this->auth->setUserID($sessionArray['user_id']);
$data['userInfo'] = $this->auth->getUserDetails();
$this->page_construct('auth/index', $data);
}
}
// registration method
public function register() {
$data = array();
$data['metaDescription'] = 'New User Registration';
$data['metaKeywords'] = 'New User Registration';
$data['title'] = "Registration - TechArise";
$data['breadcrumbs'] = array('Registration' => '#');
$this->page_construct('auth/register', $data);
}
// edit method
public function edit() {
if ($this->session->userdata('ci_session_key_generate') == FALSE) {
redirect('signin'); // the user is not logged in, redirect them!
} else {
$data = array();
$data['metaDescription'] = 'Update Profile';
$data['metaKeywords'] = 'Update Profile';
$data['title'] = "Update Profile - TechArise";
$data['breadcrumbs'] = array('Update Profile' => '#');
$sessionArray = $this->session->userdata('ci_seesion_key');
$this->auth->setUserID($sessionArray['user_id']);
$data['userInfo'] = $this->auth->getUserDetails();
$this->page_construct('auth/edit', $data);
}
}
// login method
public function login() {
if (!empty($this->input->get('usid'))) {
$verificationCode = urldecode(base64_decode($this->input->get('usid')));
$this->auth->setVerificationCode($verificationCode);
$this->auth->activate();
}
$data = array();
$data['metaDescription'] = 'Login';
$data['metaKeywords'] = 'Login';
$data['title'] = "Login - TechArise";
$data['breadcrumbs'] = array('Login' => '#');
$this->page_construct('auth/login', $data);
}
// edit method
public function changepwd() {
if ($this->session->userdata('ci_session_key_generate') == FALSE) {
redirect('signin'); // the user is not logged in, redirect them!
} else {
$data = array();
$data['metaDescription'] = 'New User Registration';
$data['metaKeywords'] = 'Change Password';
$data['title'] = "Change Password - TechArise";
$data['breadcrumbs'] = array('Change Password' => '#');
$this->page_construct('auth/changepwd', $data);
}
}
//forgot password method
public function forgotpassword() {
if ($this->session->userdata('ci_session_key_generate') == TRUE) {
redirect('profile'); // the user is logged in, redirect them!
} else {
$data['metaDescription'] = 'Forgot Password';
$data['metaKeywords'] = 'Member, forgot password';
$data['title'] = "Forgot Password - SoOLEGAL";
$data['breadcrumbs'] = array('Forgot Password' => '#');
$this->page_construct('auth/forgotpwd', $data);
}
}
// action create user method
public function actionCreate() {
$this->form_validation->set_rules('first_name', 'First Name', 'required');
$this->form_validation->set_rules('last_name', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('contact_no', 'Contact No', 'required|regex_match[/^[0-9]{10}$/]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]');
$this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'trim|required|matches[password]');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('dob', 'Date of Birth(DD-MM-YYYY)', 'required');
if ($this->form_validation->run() == FALSE) {
$this->register();
} else {
$firstName = $this->input->post('first_name');
$lastName = $this->input->post('last_name');
$email = $this->input->post('email');
$password = $this->input->post('password');
$contactNo = $this->input->post('contact_no');
$dob = $this->input->post('dob');
$address = $this->input->post('address');
$timeStamp = time();
$status = 0;
$verificationCode = uniqid();
$verificationLink = site_url() . 'signin?usid=' . urlencode(base64_encode($verificationCode));
$userName = $this->mail->generateUnique('users', trim($firstName . $lastName), 'user_name', NULL, NULL);
$this->auth->setUserName($userName);
$this->auth->setFirstName(trim($firstName));
$this->auth->setLastName(trim($lastName));
$this->auth->setEmail($email);
$this->auth->setPassword($password);
$this->auth->setContactNo($contactNo);
$this->auth->setAddress($address);
$this->auth->setDOB($dob);
$this->auth->setVerificationCode($verificationCode);
$this->auth->setTimeStamp($timeStamp);
$this->auth->setStatus($status);
$chk = $this->auth->create();
if ($chk === TRUE) {
$this->load->library('encrypt');
$mailData = array('topMsg' => 'Hi', 'bodyMsg' => 'Congratulations, Your registration has been successfully submitted.', 'thanksMsg' => SITE_DELIMETER_MSG, 'delimeter' => SITE_DELIMETER, 'verificationLink' => $verificationLink);
$this->mail->setMailTo($email);
$this->mail->setMailFrom(MAIL_FROM);
$this->mail->setMailSubject('User Registeration!');
$this->mail->setMailContent($mailData);
$this->mail->setTemplateName('verification');
$this->mail->setTemplatePath('mailTemplate/');
$chkStatus = $this->mail->sendMail(MAILING_SERVICE_PROVIDER);
if ($chkStatus === TRUE) {
redirect('signin');
} else {
echo 'Error';
}
} else {
}
}
}
// action update user
public function editUser() {
$this->form_validation->set_rules('first_name', 'First Name', 'required');
$this->form_validation->set_rules('last_name', 'Last Name', 'required');
$this->form_validation->set_rules('contact_no', 'Contact No', 'required|regex_match[/^[0-9]{10}$/]');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('dob', 'Date of Birth(DD-MM-YYYY)', 'required');
if ($this->form_validation->run() == FALSE) {
$this->edit();
} else {
$firstName = $this->input->post('first_name');
$lastName = $this->input->post('last_name');
$contactNo = $this->input->post('contact_no');
$dob = $this->input->post('dob');
$address = $this->input->post('address');
$timeStamp = time();
$sessionArray = $this->session->userdata('ci_seesion_key');
$this->auth->setUserID($sessionArray['user_id']);
$this->auth->setFirstName(trim($firstName));
$this->auth->setLastName(trim($lastName));
$this->auth->setContactNo($contactNo);
$this->auth->setAddress($address);
$this->auth->setDOB($dob);
$this->auth->setTimeStamp($timeStamp);
$status = $this->auth->update();
if ($status == TRUE) {
redirect('profile');
}
}
}
// action login method
function doLogin() {
// Check form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('user_name', 'User Name/Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->login;
} else {
$sessArray = array();
//Field validation succeeded. Validate against database
$username = $this->input->post('user_name');
$password = $this->input->post('password');
$this->auth->setUserName($username);
$this->auth->setPassword($password);
//query the database
$result = $this->auth->login();
if (!empty($result) && count($result) > 0) {
foreach ($result as $row) {
$authArray = array(
'user_id' => $row->user_id,
'user_name' => $row->user_name,
'email' => $row->email
);
$this->session->set_userdata('ci_session_key_generate', TRUE);
$this->session->set_userdata('ci_seesion_key', $authArray);
}
redirect('profile');
} else {
redirect('signin?msg=1');
}
}
}
public function actionChangePwd() {
$this->form_validation->set_rules('change_pwd_password', 'Password', 'trim|required|min_length[8]');
$this->form_validation->set_rules('change_pwd_confirm_password', 'Password Confirmation', 'trim|required|matches[change_pwd_password]');
if ($this->form_validation->run() == FALSE) {
$this->changepwd();
} else {
$change_pwd_password = $this->input->post('change_pwd_password');
$sessionArray = $this->session->userdata('ci_seesion_key');
$this->auth->setUserID($sessionArray['user_id']);
$this->auth->setPassword($change_pwd_password);
$status = $this->auth->changePassword();
if ($status == TRUE) {
redirect('profile');
}
}
}
//action forgot password method
public function actionForgotPassword() {
$this->form_validation->set_rules('forgot_email', 'Your Email', 'trim|required|valid_email');
if ($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to Forgot Password page
$this->forgotpassword();
} else {
$login = site_url() . 'signin';
$email = $this->input->post('forgot_email');
$this->auth->setEmail($email);
$pass = $this->generateRandomPassword(8);
$this->auth->setPassword($pass);
$status = $this->auth->updateForgotPassword();
if ($status == TRUE) {
$this->load->library('encrypt');
$mailData = array('topMsg' => 'Hi', 'bodyMsg' => 'Your password has been reset successfully!.', 'thanksMsg' => SITE_DELIMETER_MSG, 'delimeter' => SITE_DELIMETER, 'loginLink' => $login, 'pwd' => $pass, 'username' => $email);
$this->mail->setMailTo($email);
$this->mail->setMailFrom(MAIL_FROM);
$this->mail->setMailSubject('Forgot Password!');
$this->mail->setMailContent($mailData);
$this->mail->setTemplateName('sendpwd');
$this->mail->setTemplatePath('mailTemplate/');
$chkStatus = $this->mail->sendMail(MAILING_SERVICE_PROVIDER);
if ($chkStatus === TRUE) {
redirect('forgotpwd?msg=2');
} else {
redirect('forgotpwd?msg=1');
}
} else {
redirect('forgotpwd?msg=1');
}
}
}
//generate random password
public function generateRandomPassword($length = 10) {
$alphabets = range('a', 'z');
$numbers = range('0', '9');
$final_array = array_merge($alphabets, $numbers);
$password = '';
while ($length--) {
$key = array_rand($final_array);
$password .= $final_array[$key];
}
return $password;
}
//logout method
public function logout() {
$this->session->unset_userdata('ci_seesion_key');
$this->session->unset_userdata('ci_session_key_generate');
$this->session->sess_destroy();
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
redirect('signin');
}
}
?>
Step 7: Create mailing class with
SMTP
(Simple Mail Transfer Protocol) functionalityCreate a model file named
"Mail.php"
inside “application/models”
folder.
/* * ***
* Version: V1.0.1
*
* Description of Mail model
*
* @author TechArise Team
*
* @email info@techarise.com
*
* *** */
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Mail extends CI_Model {
// Declaration of a variables
private $_mailTo;
private $_mailFrom;
private $_mailSubject;
private $_mailContent;
private $_templateName;
private $_templatePath;
//Declaration of a methods
public function setMailTo($mailTo) {
$this->_mailTo = $mailTo;
}
public function setMailFrom($mailFrom) {
$this->_mailFrom = $mailFrom;
}
public function setMailSubject($mailSubject) {
$this->_mailSubject = $mailSubject;
}
public function setMailContent($mailContent) {
$this->_mailContent = $mailContent;
}
public function setTemplateName($templateName) {
$this->_templateName = $templateName;
}
public function setTemplatePath($templatePath) {
$this->_templatePath = $templatePath;
}
// smtpMail
public function sendMail($data) {
//Load email library
$this->load->library('email');
if (!empty($data) && $data == 'smtp') {
//SMTP & mail configuration
$config = array(
'protocol' => PROTOCOL,
'smtp_host' => SMTP_HOST,
'smtp_port' => SMTP_PORT,
'smtp_user' => SMTP_USER,
'smtp_pass' => SMTP_PASS,
'mailtype' => MAILTYPE,
'charset' => CHARSET,
);
$fullPath = $this->_templatePath . $this->_templateName;
$this->email->initialize($config);
$this->email->set_mailtype(MAILTYPE);
$this->email->set_newline("\r\n");
//Email content
$mailMessage = $this->load->view($fullPath, $this->_mailContent, TRUE);
$this->email->to($this->_mailTo);
$this->email->from($this->_mailFrom, FROM_TEXT);
$this->email->subject($this->_mailSubject);
$this->email->message($mailMessage);
//Send email
if ($this->email->send()) {
return TRUE;
} else {
return FALSE;
}
}
}
// generate Unique UserName
public function generateUnique($tableName, $string, $field, $key = NULL, $value = NULL) {
$slug = preg_replace('/[^A-Za-z0-9-]+/', '', strtolower($string));
$i = 0;
$params = array();
$params[$field] = $slug;
if ($key)
$params["$key !="] = $value;
while ($this->db->where($params)->get($tableName)->num_rows()) {
if (!preg_match('/-{1}[0-9]+$/', $slug))
$slug .= '-' . ++$i;
else
$slug = preg_replace('/[0-9]+$/', ++$i, $slug);
$params [$field] = $slug;
}
return $slug;
}
}
?>
Step 8: Create views for registration
Create a views file named
register.php
inside “application/views/auth”
folder.Step 9: Create views for login
Create a views file named
login.php
inside “application/views/auth”
folder.
Login Form
input->get('msg')) && $this->input->get('msg') == 1) { ?>
Please Enter Your Valid Information.
Step 10: Create views for Forgot Password
Create a views file named
forgotpwd.php
inside “application/views/auth”
folder.
Forgot Password
input->get('msg')) && $this->input->get('msg') == 1) { ?>
Please Enter Your Valid Information.
input->get('msg')) && $this->input->get('msg') == 2) { ?>
Your password has been reset successfully. Please check your email.
Step 11: Create views for profile page
Create a views file named
index.php
inside “application/views/auth”
folder.Step 12: Create views for edit profile page
Create a views file named
edit.php
inside “application/views/auth”
folder.
Profile
Step 13: Create views for change password page
Create a views file named
changepwd.php
inside “application/views/auth”
folder.
Setting
input->get('msg')) && $this->input->get('msg') == 1) { ?>
Please Enter Your Valid Information.
Demo [sociallocker] Download[/sociallocker]