In this article, we will explain to you how to create a User Login logout and register example in Codeigniter Framework. Sometimes when creating an admin panel at that time we need to Registration, Login, and logout into Codeigniter.
here, we will give you a simple example of how to create a Login logout and register example in Codeigniter. so you can see the below example.
Overview
Step 1: Create a Database in table
Step 2: Connect to Database
Step 3: Create Controller
Step 4: Create a Model
Step 5: Create View File
Step 1: Create a Database in table
In this step, we have to create a table in the database, so we will create a database using the below code.
CREATE TABLE `users` ( `user_id` int(255) NOT NULL, `user_first_name` varchar(255) NOT NULL, `user_last_name` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_password` varchar(255) NOT NULL, `user_register_status` int(1) NOT NULL DEFAULT '0', `user_token` varchar(255) NOT NULL, `user_created` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; COMMIT;
Step 2: Connect to Database
Go to the config folder and open database.php file some changes in this file like hostname, database username, database password, and database name.
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'enter here 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: Create Controller
In this step, we will create a Login.php, Logout.php, and Dashboard.php file in the “application/controller” directory and paste the below code in this controller.
application/controller/Login.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('common_model'); $set_session = $this->session->userdata('logged_in'); if ($set_session != 0) { redirect('dashboard'); } } public function index() { $this->load->view('login'); } public function check() { if (isset($_POST['btnLogin'])) { $email = $_POST['txtEmail']; $password = $_POST['txtPassword']; $res = $this->common_model->verifyuser($email, $password); if (!empty($res)) { $ses_user = array( "user_id" => $res['user_id'], "user_first_name" => $res['user_first_name'], "user_last_name" => $res['user_last_name'], "user_email" => $res['user_email'], "logged_in" => 1 ); $this->session->set_userdata($ses_user); redirect('login'); } else { $ses_user = array("logged_in" => 0); $this->session->set_userdata($ses_user); $this->session->set_flashdata('error', 'Invalid Usename or Password !!'); redirect('login'); } } } public function register() { if ($this->input->post('btnRegister')) { $arrData["user_first_name"] = $_POST['txtFname']; $arrData["user_last_name"] = $_POST['txtLname']; $arrData["user_email"] = $_POST['txtEmail']; $arrData["user_password"] = md5($_POST['txtPassword']); $arrData["user_token"] = md5(time()); $arrData["user_created"] = date('Y-m-d H:i:s'); $last_insertId = $this->common_model->insert_and_get_last_inserted_id('users',$arrData); if ($last_insertId) { $this->session->set_flashdata('success', 'Register Successfully !!'); redirect('login'); } else { $this->session->set_flashdata('error', 'Failed to Register !!'); redirect('login/register'); } } $this->load->view('register'); } public function unique_email() { $que = 'SELECT user_email FROM users WHERE user_email = "' . $_POST['txtEmail'] . '"'; $query1 = $this->db->query($que)->result_array(); if (!empty($query1)) { echo 'true'; } else { echo 'false'; } } public function already_exists() { $que = 'SELECT user_email FROM users WHERE user_email = "' . $_POST['txtEmail'] . '"'; $query1 = $this->db->query($que)->result_array(); if (!empty($query1)) { echo 'false'; } else { echo 'true'; } } }
application/controller/Logout.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Logout extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('session'); } public function index() { $this->session->sess_destroy(); redirect('login','refresh'); } } ?>
application/controller/Dashboard.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dashboard extends CI_Controller { function __construct(){ parent::__construct(); $set_session = $this->session->userdata('logged_in'); if($set_session == 0){ redirect('login'); } } public function index() { $arrData['middle'] = "dashboard"; $this->load->view('template',$arrData); } } ?>
Step 4: Create a Model
In this step, we will create a Common_model.php file in the “application/models” directory and paste the below code in this model.
application/models/Common_model.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Common_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } function verifyuser($email,$pass) { $this->db->select('*'); $this->db->where('user_email',$email); $this->db->where('user_password',md5($pass)); $this->db->limit('1'); $query = $this->db->get('users'); $row = $query->row_array(); return $row; } public function insert($table,$product_data) { if($this->db->insert($table,$product_data)) { return true; } else { return false; } } public function insert_and_get_last_inserted_id($table,$product_data) { if($this->db->insert($table,$product_data)) { return $this->db->insert_id(); } else { return false; } } public function update($table,$where_array,$update) { $this->db->where($where_array); if($this->db->update($table,$update)) { return true; } else { return false; } } public function delete_data($table,$where) { if($this->db->delete($table,$where)) { return true; } else { return false; } } } ?>
Step 5: Create View File
So finally, we will create the login.php file in the “application/views/” directory.
application/views/login.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Login</title> <!-- Custom fonts for this template--> <link href="<?php echo base_url(); ?>assets/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Custom styles for this template--> <link href="<?php echo base_url(); ?>assets/css/sb-admin.css" rel="stylesheet"> </head> <body class="bg-dark"> <div class="container"> <div class="row"> <div class="col-sm-12"> <?php if ($this->session->flashdata('success')){ ?> <div class="alert alert-success alert-dismissable" style="margin-top: 30px;"> <!-- a title="Hide Notification" class="close-notification tooltip" href="#">x</a --> <a href="#" class="close pull-right" data-dismiss="alert" aria-label="close">×</a> <h4>Success</h4> <p><?php echo $this->session->flashdata('success') ?></p> </div> <?php } ?> <?php if ($this->session->flashdata('error')){ ?> <div class="alert alert-danger alert-dismissable" style="margin-top: 30px;"> <!-- a title="Hide Notification" class="close-notification tooltip" href="#">x</a --> <a href="#" class="close pull-right" data-dismiss="alert" aria-label="close">×</a> <h4>Error</h4> <p><?php echo $this->session->flashdata('error') ?></p> </div> <?php } ?> </div> </div> <div class="card card-login mx-auto mt-5"> <div class="card-header">Login</div> <div class="card-body"> <form name="frmLogin" id="frmLogin" method="post" action="<?php echo base_url('login/check'); ?>"> <div class="form-group"> <div class="form-label-group"> <input type="email" name="txtEmail" id="txtEmail" class="form-control" placeholder="Email address" required="required" autofocus="autofocus"> <label for="txtEmail">Email address</label> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="password" name="txtPassword" id="txtPassword" class="form-control" placeholder="Password" required="required"> <label for="txtPassword">Password</label> </div> </div> <div class="form-group"> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember Password </label> </div> </div> <input type="submit" class="btn btn-primary btn-block" id="btnLogin" name="btnLogin" value="Login"> </form> <div class="text-center"> <a class="d-block small mt-3" href="<?php echo base_url('login/register'); ?>">Register an Account</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <script src="<?php echo base_url();?>assets/js/jquery.validate.js"></script> <script> $(document).ready(function () { var base_url = "<?php echo base_url();?>"; $("#frmLogin").validate({ rules:{ txtEmail: { required:true, email:true, remote: { url: base_url + 'login/unique_email', type: "post", data: { txtEmail: function () { return $("#txtEmail").val(); } } } }, txtPassword: { required:true } }, messages: { txtEmail: { remote:'This email is not an exists.' } }, submitHandler: function(form) { form.submit(); return true // } } }); }); </script> </body> </html>
application/views/register.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Register</title> <!-- Custom fonts for this template--> <link href="<?php echo base_url(); ?>assets/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Custom styles for this template--> <link href="<?php echo base_url(); ?>assets/css/sb-admin.css" rel="stylesheet"> </head> <body class="bg-dark"> <div class="container"> <div class="card card-register mx-auto mt-5"> <div class="card-header">Register an Account</div> <div class="card-body"> <form name="frmRegister" id="frmRegister" method="post" action="<?php echo base_url('login/register'); ?>"> <div class="form-group"> <div class="form-row"> <div class="col-md-6"> <div class="form-label-group"> <input type="text" id="txtFname" name="txtFname" class="form-control" placeholder="First name" required="required" autofocus="autofocus"> <label for="txtFname">First name</label> </div> </div> <div class="col-md-6"> <div class="form-label-group"> <input type="text" id="txtLname" name="txtLname" class="form-control" placeholder="Last name" required="required"> <label for="txtLname">Last name</label> </div> </div> </div> </div> <div class="form-group"> <div class="form-label-group"> <input type="email" id="txtEmail" name="txtEmail" class="form-control" placeholder="Email address" required="required"> <label for="txtEmail">Email address</label> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-6"> <div class="form-label-group"> <input type="password" id="txtPassword" name="txtPassword" class="form-control" placeholder="Password" required="required"> <label for="txtPassword">Password</label> </div> </div> <div class="col-md-6"> <div class="form-label-group"> <input type="password" id="txtCpassword" name="txtCpassword" class="form-control" placeholder="Confirm password" required="required"> <label for="txtCpassword">Confirm password</label> </div> </div> </div> </div> <input type="submit" class="btn btn-primary btn-block" id="btnRegister" name="btnRegister" value="Register"> </form> <div class="text-center"> <a class="d-block small mt-3" href="<?php echo base_url('login'); ?>">Login Page</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <script src="<?php echo base_url();?>assets/js/jquery.validate.js"></script> <script> $(document).ready(function () { var base_url = "<?php echo base_url();?>"; $("#frmRegister").validate({ rules:{ txtFname:{ required:true }, txtFname:{ required:true }, txtEmail: { required:true, email:true, remote: { url: base_url + 'login/already_exists', type: "post", data: { txtEmail: function () { return $("#txtEmail").val(); } } } }, txtPassword: { required:true }, txtCpassword: { required:true, equalTo: "#txtPassword" } }, messages: { txtEmail: { remote:'This email is an already exists.' } }, submitHandler: function(form) { form.submit(); return true } }); }); </script> </body> </html>
application/views/dashboard.php
<div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="#">Dashboard</a> </li> <li class="breadcrumb-item active">Overview</li> </ol> <!-- Icon Cards--> <div class="row"> <div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-primary o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-fw fa-comments"></i> </div> <div class="mr-5">26 New Messages!</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fas fa-angle-right"></i> </span> </a> </div> </div> <div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-warning o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-fw fa-list"></i> </div> <div class="mr-5">11 New Tasks!</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fas fa-angle-right"></i> </span> </a> </div> </div> <div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-success o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-fw fa-shopping-cart"></i> </div> <div class="mr-5">123 New Orders!</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fas fa-angle-right"></i> </span> </a> </div> </div> <div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-danger o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-fw fa-life-ring"></i> </div> <div class="mr-5">13 New Tickets!</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fas fa-angle-right"></i> </span> </a> </div> </div> </div> <!-- Area Chart Example--> <div class="card mb-3"> <div class="card-header"> <i class="fas fa-chart-area"></i> Area Chart Example</div> <div class="card-body"> <canvas id="myAreaChart" width="100%" height="30"></canvas> </div> <div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div> </div> <!-- DataTables Example --> <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Data Table Example</div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior Javascript Developer</td> <td>Edinburgh</td> <td>22</td> <td>2012/03/29</td> <td>$433,060</td> </tr> </tbody> </table> </div> </div> <div class="card-footer small text-muted">Updated yesterday at 11:59 PM</div> </div> </div> <!-- /.container-fluid -->
application/views/template.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin - Dashboard</title> <!-- Custom fonts for this template--> <link href="<?php echo base_url(); ?>assets/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="<?php echo base_url(); ?>assets/vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <!-- Custom styles for this template--> <link href="<?php echo base_url(); ?>assets/css/sb-admin.css" rel="stylesheet"> </head> <body id="page-top"> <nav class="navbar navbar-expand navbar-dark bg-dark static-top"> <a class="navbar-brand mr-1" href="<?php echo base_url(); ?>">Start Bootstrap</a> <button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#"> <i class="fas fa-bars"></i> </button> <!-- Navbar Search --> <form class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-primary" type="button"> <i class="fas fa-search"></i> </button> </div> </div> </form> <!-- Navbar --> <ul class="navbar-nav ml-auto ml-md-0"> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-bell fa-fw"></i> <span class="badge badge-danger">9+</span> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="alertsDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item dropdown no-arrow mx-1"> <a class="nav-link dropdown-toggle" href="#" id="messagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-envelope fa-fw"></i> <span class="badge badge-danger">7</span> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="messagesDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item dropdown no-arrow"> <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-user-circle fa-fw"></i> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown"> <a class="dropdown-item" href="#">Settings</a> <a class="dropdown-item" href="#">Activity Log</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">Logout</a> </div> </li> </ul> </nav> <div id="wrapper"> <!-- Sidebar --> <ul class="sidebar navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="<?php echo base_url(); ?>"> <i class="fas fa-fw fa-tachometer-alt"></i> <span>Dashboard</span> </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="pagesDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-fw fa-folder"></i> <span>Users</span> </a> <div class="dropdown-menu" aria-labelledby="pagesDropdown"> <h6 class="dropdown-header">Users:</h6> <a class="dropdown-item" href="#">List</a> <a class="dropdown-item" href="#">Add</a> </div> </li> </ul> <div id="content-wrapper"> <?php $this->load->view($middle);?> <!-- Sticky Footer --> <footer class="sticky-footer"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright © Your Website 2019</span> </div> </div> </footer> </div> <!-- /.content-wrapper --> </div> <!-- /#wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="<?php echo base_url('logout'); ?>">Logout</a> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Page level plugin JavaScript--> <script src="<?php echo base_url(); ?>assets/vendor/chart.js/Chart.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/datatables/jquery.dataTables.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/datatables/dataTables.bootstrap4.js"></script> <!-- Custom scripts for all pages--> <script src="<?php echo base_url(); ?>assets/js/sb-admin.min.js"></script> <!-- Demo scripts for this page--> <script src="<?php echo base_url(); ?>assets/js/demo/datatables-demo.js"></script> <script src="<?php echo base_url(); ?>assets/js/demo/chart-area-demo.js"></script> </body> </html>
We think would you like this article, so you can click on the “Show Demo” button and you can see this demo article.