Create Login Form with CodeIgniter and MySQL
The most common way of authenticating a user in web applications is through a login form. It is usually used to check the authenticity of the use. In this tutorial, we will create a simple login system using CodeIgniter and MySQL. So here we have handled login functionality by creating a simple login form in CodeIgniter and Bootstrap Framework along with MySQL Database. This is a very simple example, you can just copy-paste and change according to your requirement.
Before started to implement the Create Login using CodeIgniter, look files structure:
- create-login-form-with-codeigniter
- application
- config
- autoload.php
- constants.php
- routes.php
- models
- Users_model.php
- controllers
- Users.php
- views
- users
- thank-you.php
- index.php
- templates
- header.php
- footer.php
- users
- config
- system
- index.php
- assets
- images
- css
- style.css
- application
Step 1: Create the Database and Table
For this tutorial, you need a MySQL database with the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php CREATE TABLE `users` ( `user_id` int(12) NOT NULL, `name` varchar(50) DEFAULT NULL, `user_name` varchar(50) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `status` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `email` (`email`); ALTER TABLE `users` MODIFY `user_id` int(12) NOT NULL AUTO_INCREMENT; COMMIT; ?> |
Step 2: Configure Database access
Update the file application/config/database.php in your CodeIgniter installation with your database info:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php // configure database $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', // Your username if required. 'password' => '', // Your password if any. 'database' => 'demo_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.
1 2 3 4 |
<?php // create routes $route['login'] = 'users/login'; ?> |
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.
1 2 3 4 5 6 |
<?php // load libraries $autoload['libraries'] = array('database','session'); // load helper $autoload['helper'] = array('url'); ?> |
Step 5: Create Model
Create a model file named Users_model.php inside “application/models” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php /** * Description of Users Model * * @author Team TechArise * * @email info@techarise.com */ defined('BASEPATH') or exit('No direct script access allowed'); class Users_model extends CI_Model { // declare private variable private $_userID; private $_name; private $_userName; private $_email; private $_password; private $_status; public function setUserID($userID) { $this->_userID = $userID; } public function setName($name) { $this->_name = $name; } public function setUserName($userName) { $this->_userName = $userName; } public function setEmail($email) { $this->_email = $email; } public function setPassword($password) { $this->_password = $password; } public function setStatus($status) { $this->_status = $status; } public function getUserInfo() { $this->db->select(array('u.user_id', 'u.user_name', 'u.name', 'u.email')); $this->db->from('users as u'); $this->db->where('u.user_id', $this->_userID); $query = $this->db->get(); return $query->row_array(); } function login() { $this->db->select('user_id, name, email'); $this->db->from('users'); $this->db->where('email', $this->_email); $this->db->where('password', $this->_password); $this->db->limit(1); $query = $this->db->get(); if ($query->num_rows() == 1) { return $query->result(); } else { return false; } } } ?> |
Step 6: Create controllers
Create a controllers file named Users.php inside “application/controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<?php /** * Description of Users Controller * * @author Team TechArise * * @email info@techarise.com */ defined('BASEPATH') or exit('No direct script access allowed'); class Users extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Users_model', 'user'); } // Dashboard method public function index() { if ($this->session->userdata('is_authenticated') == FALSE) { redirect('users/login'); // the user is not logged in, redirect them! } else { $data['title'] = 'Dashboard - Tech Arise'; $data['metaDescription'] = 'Dashboard'; $data['metaKeywords'] = 'Dashboard'; $this->user->setUserID($this->session->userdata('user_id')); $data['userInfo'] = $this->user->getUserInfo(); $this->load->view('users/thank-you', $data); } } // Login method public function login() { if ($this->session->userdata('is_authenticated') == TRUE) { redirect('users/index'); // the user is not logged in, redirect them! } else { $data['title'] = 'Login - Tech Arise'; $data['metaDescription'] = 'Login'; $data['metaKeywords'] = 'Login'; $this->load->view('users/index', $data); } } // Login Action function doLogin() { // Check form validation $this->load->library('form_validation'); $this->form_validation->set_rules('email', 'Your Email', 'trim|required|valid_email'); $this->form_validation->set_rules('password', 'Password', 'trim|required'); if ($this->form_validation->run() == FALSE) { //Field validation failed. User redirected to login page $this->load->view('users/login'); } else { $sessArray = array(); //Field validation succeeded. Validate against database $email = $this->input->post('email'); $password = $this->input->post('password'); $this->user->setEmail($email); $this->user->setPassword(MD5($password)); //query the database $result = $this->user->login(); if ($result) { foreach ($result as $row) { $sessArray = array( 'user_id' => $row->user_id, 'name' => $row->name, 'email' => $row->email, 'is_authenticated' => TRUE, ); $this->session->set_userdata($sessArray); } redirect('users'); } else { redirect('users/login?msg=1'); } } } // Logout public function logout() { $this->session->unset_userdata('user_id'); $this->session->unset_userdata('name'); $this->session->unset_userdata('email'); $this->session->unset_userdata('is_authenticated'); $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('/'); } } ?> |
Step 7: Create views
Create a views file named index.php inside “application/views/users” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php $this->load->view('templates/header'); ?> <main role="main" class="container mcontainer"> <div class="wrapper"> <form action="<?php echo base_url(); ?>users/dologin" method="post" id="loginform" name="Login_Form" class="form-signin" method="POST"> <h4 class="form-signin-heading">Create Login Form with CodeIgniter</h4> <?php if (validation_errors()) { ?> <div class="alert alert-danger"> <?php echo validation_errors(); ?> </div> <?php } ?> <?php if (!empty($this->input->get('msg')) && $this->input->get('msg') == 1) { ?> <div class="alert alert-danger"> Please Enter Your Valid Information. </div> <?php } ?> <?php if (validation_errors()) { ?> <div class="alert alert-danger"> <?php echo validation_errors(); ?> </div> <?php } ?> <div class="form-group"> <label for="name">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="Email*" required /> </div> <div class="form-group"> <label for="name">Password</label> <input type="password" class="form-control" id="password" name="password" placeholder="Password" required /> </div> <button type="submit" class="btn btn-primary" style="float:right">Login</button> </form> </div> </main> <?php $this->load->view('templates/footer'); ?> |
Step 7: Create views
Create a views file named thank-you.php inside “application/views/users” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $this->load->view('templates/header'); ?> <main role="main" class="container mcontainer"> <div class="wrapper thank-you-page"> <div class="thank-you-pop"> <img src="<?php echo HTTP_IMAGES_PATH; ?>tick.png" alt=""> <h1>Dashboard</h1> <h3 class="cupon-pop">Welcome: <span><?php if(!empty($userInfo)) { print $userInfo['name']; } else {print "User"; }?></span></h3> </div> <hr> <div class="row"> <div class="col-lg-8 offset-2"> <a href="<?php echo base_url(); ?>" class="btn btn-sm btn-primary" style="float:right"><i class="fa fa-user"></i> Register</a> <a class="btn btn-primary btn-sm" href="<?php echo base_url(); ?>create-registration-form-with-codeigniter-and-bootstrap/"><i class="fa fa-mail-reply"></i> Back To Tutorial</a> </div> </div> </div> </main> <?php $this->load->view('templates/footer'); ?> |