Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
Part 7
User authentication is a required feature of any Web application. Based on user authentication user can access the system by providing their user authentication details. So, in this post we are login to learn Complete user registration and login system in Codeigniter framework. If you have use Codeigniter Framework to your web project, then in that project you want to add give rights to user to register into your system, after completed registration process, user can login into system by providing his login details which he has used in registration process. If login details are proper then user can access system. So here we will make complete user authentication system in Codeigniter in which user can registration into system and login into system features. Here you can learn this login and registration functionality in Codeigniter framework.
If you are start learning Codeigniter framework for web devlopment, then you must have to learn User Register and Login system which is most required feature of any web based application, so you have to must learn this system in Codeigniter, so you can make web based application in Codeigniter in which you can add this User register and Login system. Codeigniter framework has many build-in libraries and helper class which will very helpful to make user authentication system. In this post we will use Codeigniter database library, session library, form validation library, email library for sending verification email address link, encrypt library for convert simple password into hash formatted password. We will also use Codeigniter url helper, form helper for make this user register and login system in Codeigniter framework.
Here we will make user registration and login system using Session in Codeigniter framework. In this post you can find step by step process for make user registration and login system in Codeigniter with Session library with Mysql database. In this system you can find following features of User Registration and Login system using Codeigniter framework with Mysql database.
See Also
- User Registration form to submit user details and Insert into Mysql Database
- Send email verification email to registered email address for email verification
- Convert user simple password to hash string for user authentication
- Register and Login form data validation
- Check email already registered or not at the time of user registration
- User login form for access into system
- Store user authentication details in Session
- User logout from system
Database table creation
For store user information, we have to required table in mysql table, following script will make table in mysql database.
--
-- Database: `testing`
--
-- --------------------------------------------------------
--
-- Table structure for table `codeigniter_register`
--
CREATE TABLE `codeigniter_register` (
`id` int(11) NOT NULL,
`name` varchar(250) NOT NULL,
`email` varchar(250) NOT NULL,
`password` text NOT NULL,
`verification_key` varchar(250) NOT NULL,
`is_email_verified` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `codeigniter_register`
--
ALTER TABLE `codeigniter_register`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `codeigniter_register`
--
ALTER TABLE `codeigniter_register`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Autoload Libraries & Helper
In User Register and Login system in Codeigniter, we have to load some libraries and helper at the time of first code execution. For this we have to open application/cofig/autoload.php file and load following files and helper.
autoload.php
$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url','form');
Database Connection
After load of required library and helper, we want to make database connection, for this we have to open application/config/database.php file and write following database configuration.
database.php
<?php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'testing',
'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
);
?>
Controllers (Register.php)
This controller is used for handles all register replated functionality.
_construct() - This function is used for load form validation and encrypt library, register model at the time of new object of this class has been created.
index() - This function will load register form in browser.
validation() - This function has received register form request, in this function first we have validate form data using Codeigniter form validation library. After success validation of form data, it will proceed for insert data into mysql table. After successfully insert of register form data, this function will generate dynamic email verification email with dynamic email verification link and send email to registered email address using Codeigniter email library.
verify_email() - This function is used for verify email address, this function received request for email verification from email verification link. Once email has been verified user can login into system.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
if($this->session->userdata('id'))
{
redirect('private_area');
}
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->model('register_model');
}
function index()
{
$this->load->view('register');
}
function validation()
{
$this->form_validation->set_rules('user_name', 'Name', 'required|trim');
$this->form_validation->set_rules('user_email', 'Email Address', 'required|trim|valid_email|is_unique[codeigniter_register.email]');
$this->form_validation->set_rules('user_password', 'Password', 'required');
if($this->form_validation->run())
{
$verification_key = md5(rand());
$encrypted_password = $this->encrypt->encode($this->input->post('user_password'));
$data = array(
'name' => $this->input->post('user_name'),
'email' => $this->input->post('user_email'),
'password' => $encrypted_password,
'verification_key' => $verification_key
);
$id = $this->register_model->insert($data);
if($id > 0)
{
$subject = "Please verify email for login";
$message = "
<p>Hi ".$this->input->post('user_name')."</p>
<p>This is email verification mail from Codeigniter Login Register system. For complete registration process and login into system. First you want to verify you email by click this <a href='".base_url()."register/verify_email/".$verification_key."'>link</a>.</p>
<p>Once you click this link your email will be verified and you can login into system.</p>
<p>Thanks,</p>
";
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'smtpout.secureserver.net',
'smtp_port' => 80,
'smtp_user' => 'xxxxxxx',
'smtp_pass' => 'xxxxxxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('info@webslesson.info');
$this->email->to($this->input->post('user_email'));
$this->email->subject($subject);
$this->email->message($message);
if($this->email->send())
{
$this->session->set_flashdata('message', 'Check in your email for email verification mail');
redirect('register');
}
}
}
else
{
$this->index();
}
}
function verify_email()
{
if($this->uri->segment(3))
{
$verification_key = $this->uri->segment(3);
if($this->register_model->verify_email($verification_key))
{
$data['message'] = '<h1 align="center">Your Email has been successfully verified, now you can login from <a href="'.base_url().'login">here</a></h1>';
}
else
{
$data['message'] = '<h1 align="center">Invalid Link</h1>';
}
$this->load->view('email_verification', $data);
}
}
}
?>
Controllers(Login.php)
In this Login controller you can find following function for all Login operation like, load login form, login form data verification.
_construct() - This function is used for load form validation and encrypt library, login model at the time of new object of this class has been created.
index() - This function will load Login form on web page.
validation() - This function received request for validate login details. After successfully verify user login details, page will redirect to private_area controller.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
if($this->session->userdata('id'))
{
redirect('private_area');
}
$this->load->library('form_validation');
$this->load->library('encrypt');
$this->load->model('login_model');
}
function index()
{
$this->load->view('login');
}
function validation()
{
$this->form_validation->set_rules('user_email', 'Email Address', 'required|trim|valid_email');
$this->form_validation->set_rules('user_password', 'Password', 'required');
if($this->form_validation->run())
{
$result = $this->login_model->can_login($this->input->post('user_email'), $this->input->post('user_password'));
if($result == '')
{
redirect('private_area');
}
else
{
$this->session->set_flashdata('message',$result);
redirect('login');
}
}
else
{
$this->index();
}
}
}
?>
Controller(Private_area.php)
After successfully validate login details page has been redirect to this controller. In this there following function.
_construct() - This function is used validate used login or not into system, if user not login into system then this function will redirect page to login form.
index() - This function will display Welcome user message with Logout page link.
logout() - This function will remove all session value, this function will logout user from system and redirect to login form.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Private_area extends CI_Controller {
public function __construct()
{
parent::__construct();
if(!$this->session->userdata('id'))
{
redirect('login');
}
}
function index()
{
echo '<br /><br /><br /><h1 align="center">Welcome User</h1>';
echo '<p align="center"><a href="'.base_url().'private_area/logout">Logout</a></p>';
}
function logout()
{
$data = $this->session->all_userdata();
foreach($data as $row => $rows_value)
{
$this->session->unset_userdata($row);
}
redirect('login');
}
}
?>
Models(Register_model.php)
insert() - Models function is used for database operation, So this function will insert data into Mysql table.
verify_email($key) - This model function has been used for database operation for verify email address.
<?php
class Register_model extends CI_Model
{
function insert($data)
{
$this->db->insert('codeigniter_register', $data);
return $this->db->insert_id();
}
function verify_email($key)
{
$this->db->where('verification_key', $key);
$this->db->where('is_email_verified', 'no');
$query = $this->db->get('codeigniter_register');
if($query->num_rows() > 0)
{
$data = array(
'is_email_verified' => 'yes'
);
$this->db->where('verification_key', $key);
$this->db->update('codeigniter_register', $data);
return true;
}
else
{
return false;
}
}
}
?>
Models(Login_model.php)
In this model there is only one function can_login($email, $password), this function is used to verify login form details with Mysql table details, If login details match then it will return true, otherwise it will return error message. This function convert hash password to simple string and match with Login form password.
<?php
class Login_model extends CI_Model
{
function can_login($email, $password)
{
$this->db->where('email', $email);
$query = $this->db->get('codeigniter_register');
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
if($row->is_email_verified == 'yes')
{
$store_password = $this->encrypt->decode($row->password);
if($password == $store_password)
{
$this->session->set_userdata('id', $row->id);
}
else
{
return 'Wrong Password';
}
}
else
{
return 'First verified your email address';
}
}
}
else
{
return 'Wrong Email Address';
}
}
}
?>
Views(register.php)
This html output file, which output we view on web page in browser. It will load register form on web page. In this file we have make register form, in which we have use set_value() form helper function, by using this function it can remember form data on form again load on validation error. Same way we have also use form_error() form validation library function for display form validation error on web page. Below you can find complete source code of registration form.
<!DOCTYPE html>
<html>
<head>
<title>Complete User Registration and Login System in Codeigniter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<br />
<h3 align="center">Complete User Registration and Login System in Codeigniter</h3>
<br />
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form method="post" action="<?php echo base_url(); ?>register/validation">
<div class="form-group">
<label>Enter Your Name</label>
<input type="text" name="user_name" class="form-control" value="<?php echo set_value('user_name'); ?>" />
<span class="text-danger"><?php echo form_error('user_name'); ?></span>
</div>
<div class="form-group">
<label>Enter Your Valid Email Address</label>
<input type="text" name="user_email" class="form-control" value="<?php echo set_value('user_email'); ?>" />
<span class="text-danger"><?php echo form_error('user_email'); ?></span>
</div>
<div class="form-group">
<label>Enter Password</label>
<input type="password" name="user_password" class="form-control" value="<?php echo set_value('user_password'); ?>" />
<span class="text-danger"><?php echo form_error('user_password'); ?></span>
</div>
<div class="form-group">
<input type="submit" name="register" value="Register" class="btn btn-info" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Views(email_verification.php)
This view file is used for display success message of email verification with Login link.
<!DOCTYPE html>
<html>
<head>
<title>Complete Login Register system in Codeigniter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<br />
<h3 align="center">Complete Login Register system in Codeigniter</h3>
<br />
<?php
echo $message;
?>
</div>
</body>
</html>
Views(login.php)
This view file will load Login form on web page.
<!DOCTYPE html>
<html>
<head>
<title>Complete User Registration and Login System in Codeigniter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<br />
<h3 align="center">Complete User Registration and Login System in Codeigniter</h3>
<br />
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
<?php
if($this->session->flashdata('message'))
{
echo '
<div class="alert alert-success">
'.$this->session->flashdata("message").'
</div>
';
}
?>
<form method="post" action="<?php echo base_url(); ?>login/validation">
<div class="form-group">
<label>Enter Email Address</label>
<input type="text" name="user_email" class="form-control" value="<?php echo set_value('user_email'); ?>" />
<span class="text-danger"><?php echo form_error('user_email'); ?></span>
</div>
<div class="form-group">
<label>Enter Password</label>
<input type="password" name="user_password" class="form-control" value="<?php echo set_value('user_password'); ?>" />
<span class="text-danger"><?php echo form_error('user_password'); ?></span>
</div>
<div class="form-group">
<input type="submit" name="login" value="Login" class="btn btn-info" /> <a href="<?php echo base_url(); ?>register">Register</a>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
So, this is complete source code of Codeigniter Login Register system, if you have any question regarding this tutorial, you can comment into comment box.
what is my encryption_key?
ReplyDeleteIn order to use the encryption class requires that you set an encryption key in your config file. how to solve this error?
ReplyDeleteError
ReplyDeleteThe Encrypt library requires the Mcrypt extension.
This was not working in my setup. what was routes url you use.
ReplyDeleteIf i click register button then url open http://localhost/CodeIgniter-3.1.10/register/validation
and page not found
me too
Deleteerror
ReplyDeleteThe Encrypt library requires the Mcrypt extension.
how do i add that extension?
thanks
ReplyDeleteAn Error Was Encountered
ReplyDeleteThe Encrypt library requires the Mcrypt extension.
Error ! :(
Thanks man i got lots of help
ReplyDeleteHi M Misdjan
ReplyDeleteThere is two Register.php on is Controller in controller folder and one is
view in view folder and 2nd is controller in controller folder Register.php controller Register.php is for coding and view register.php is just for designing understand!
Thanks
Error Number: 1064
ReplyDeleteYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE 0 = 'luisfilipepitapereira2001@gmail.com' LIMIT 1' at line 2
SELECT * WHERE 0 = 'luisfilipepitapereira2001@gmail.com' LIMIT 1
Filename: Z:/CodeIgniter/system/database/DB_driver.php
Line Number: 691
The good thing in OOP is that you can easily extend methods like "passwd_forget()" and other useful functions.
ReplyDeleteThey can be easily implemented by simple methods.
ReplyDeleteI will publish these extensions and will let you know.
i need the code of library email.php
ReplyDeleteHello. Great tutorial. Its my first time using Codeigniter. After i followed this tutorial, i cant access Login page. I got 403 error when i try to access this address xxxx.com/application/views/login.php. How can i fix this? Thanks.
ReplyDeleteDo you have this project to download? tks
ReplyDeletenot working.
ReplyDeleteAn Error Was Encountered
Unable to load the requested file: helpers/database_helper.php
what version of php you are using
ReplyDeleteCould you please send me the zip file and sql file to this email
ReplyDeleteAlbalbin8285@gmail.
hi can you please solve my error
ReplyDeleteAn Error Was Encountered
The Encrypt library requires the Mcrypt extension.
Thanks for share!!
ReplyDeleteWhat I miss was the Reset/Forgot password function...
plesend me zip file of this project plz
ReplyDeleteHi! Thanks. Very clear explanation.
ReplyDeleteVery Please sent me this code and the database
Hi, really clear explanation. Please sent me this code and the database?
ReplyDeletewhere is the url to download the source code?
ReplyDeletei follow your video and this blog to make registration and login system.
ReplyDeleteeverything is fine but when i am trying to login to system it says private_area page not found. and also session not working.
hi. where did you get the encryption key? thanks
ReplyDeletemake multiple step form
ReplyDeleteSir great tutorial but i face Encryption Error can u help?
ReplyDeletePlease use this for encription like md5(this->input->post(password));
DeleteAt line $this->load-library('') in file controller Register, I have to use 'encryption', because 'encrypt', I found on stack overflow, I discovered mcrypt has not been updated in years and does not support standard padding (PKCS#5 or PKCS#7) and uses null padding which will not work correctly with binary data.
ReplyDeletehttp://localhost/Codeigniter/register
ReplyDeletedoesn't get view page? help me
Sir, please give me the source code in zip file.
ReplyDeleteregister data is saved to database , but mail is not sent to user email address for email verification, please help.
ReplyDeleteAn Error Was Encountered
ReplyDeleteUnable to load the requested file: login.php
reply!
An Error Was Encountered
ReplyDeleteUnable to load the requested file: login.php
pls
Is there somewhere someone can clone this?
ReplyDelete