In this post, i am going to teach you how you can create a login and registration system in Codeigniter Framework. I am also going to attach the entire code so you can download and run it in your local system and check it immediately.
So, first of all, you need to download the Codeigniter framework and configure it in your local system.
The version I am using in this tutorial is Codeigniter 3.1.6
Download it from https://codeigniter.com/download
After you download unzip the code into your xampp or wampp and rename the folder to Codeigniter and then do the below configurations first.
Open and edit /codeigniter/application/config/config.php
$config['base_url'] = 'https://localhost/codeigniter/index.php';
then,
update your database settings in /codeigniter/application/config/database.php
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'codeigniter', '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 );
Now open phpmyadmin / mysql, and create a new database called ‘Codeigniter’ and execute the below queries:
-- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(50) NOT NULL, `date_time` 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(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
This will create a new table in your database called ‘users’.
The basic configuration is done now.
Let’s go to the coding part:
Assuming you already know that Codeigniter is an MVC framework.
First, we are going to create two models, one for login and the second one for registration.
Create files with the below names and paste the code respectively. (Read the inline comments to understand).
MODEL:
Path: /codeigniter/application/models
1) LoginModel.php
<?php class LoginModel extends CI_Model { public function checkLogin($email, $password) { //query the table 'users' and get the result count $this->db->where('email', $email); $this->db->where('password', $password); $query = $this->db->get('users'); return $query->num_rows(); } }
2) RegisterModel.php
<?php class RegisterModel extends CI_Model{ public function add_user($data){ //get the data from controller and insert into the table 'users' return $this->db->insert('users', $data); } }
VIEW:
Let’s create some view pages for our requirement. We need two pages login and registration. Also we are going to use bootstrap css for styling our pages. So first create a common header and footer all our pages.
* Create the below pages with the respective names and paste the code in it.
Path: /codeigniter/application/views
1) header.php:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> </head> <body> <div class="container">
2) footer.php:
</div> </body> </html>
Now the main pages:
3) login_page.php:
<br /> <form action="<?= base_url(); ?>login/doLogin" method="post"> <h2>Login Page</h2> <hr /> <?php if ($this->session->flashdata()) { ?> <div class="alert alert-warning"> <?= $this->session->flashdata('msg'); ?> </div> <?php } ?> <div class="form-group"> <label for="email">Email address:</label> <input type="email" name="email" required class="form-control" id="email"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" name="password" required class="form-control" id="pwd"> </div> <button type="submit" class="btn btn-default">Submit</button> <span class="float-right"><a href="<?= base_url() . 'register'; ?>" class="btn btn-primary">Register</a></span> </form>
Just a usual form with two input fields. Same as above let’s create registration page as well.
4) register_page.php:
<br /> <form action="<?= base_url(); ?>register/doRegister" method="post"> <h2>Registration</h2> <hr /> <!-- show error messages if the form validation fails --> <?php if ($this->session->flashdata()) { ?> <div class="alert alert-danger"> <?=$this->session->flashdata('errors'); ?> </div> <?php } ?> <div class="form-group"> <label for="name">Name:</label> <input type="text" name="name" required class="form-control" id="name"> </div> <div class="form-group"> <label for="email">Email address:</label> <input type="email" name="email" required class="form-control" id="email"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" name="password" required class="form-control" id="pwd"> </div> <button type="submit" class="btn btn-default">Submit</button> <span class="float-right"><a href="<?= base_url() . 'login'; ?>" class="btn btn-primary">Login</a></span> </form>
Finally, we edit the welcome_message.php:
<br /> <div class="row"> <h2>Welcome User, You are successfully logged in. </h2> <div class="col-sm-4"> <a class="btn btn-danger" href="<?=base_url().'login/logout';?>">Logout</a> </div> </div>
We are done with views now. Let’s go and create the heroes ‘Controllers’.
CONTROLLERS:
Controllers are the main heroes going to control the workflow of our code.
We need 3 controllers totally.
1.Login
2.Register
3.Welcome – (this file is already there in the Codeigniter package).
Path: /codeigniter/application/controllers
1) Login.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { public function __construct() { parent::__construct(); //load the required libraries and helpers for login $this->load->helper('url'); $this->load->library(['form_validation','session']); $this->load->database(); //load the Login Model $this->load->model('LoginModel', 'login'); } public function index() { //check if the user is already logged in $logged_in = $this->session->userdata('logged_in'); if($logged_in){ //if yes redirect to welcome page redirect(base_url().'welcome'); } //if not load the login page $this->load->view('header'); $this->load->view('login_page'); $this->load->view('footer'); } public function doLogin() { //get the input fields from login form $email = $this->input->post('email'); $password = sha1($this->input->post('password')); //send the email pass to query if the user is present or not $check_login = $this->login->checkLogin($email, $password); //if the result is query result is 1 then valid user if ($check_login) { //if yes then set the session 'loggin_in' as true $this->session->set_userdata('logged_in', true); redirect(base_url().'welcome'); } else { //if no then set the session 'logged_in' as false $this->session->set_userdata('logged_in', false); //and redirect to login page with flashdata invalid msg $this->session->set_flashdata('msg', 'Username / Password Invalid'); redirect(base_url().'login'); } } public function logout() { //unset the logged_in session and redirect to login page $this->session->unset_userdata('logged_in'); redirect(base_url().'login'); } }
Login controller helps us to validate the user credentials and store the session data. Read the inline comments to understand the code.
2) Register.php
<?php class Register extends CI_Controller { public function __construct() { parent::__construct(); //load the required helpers and libraries $this->load->helper('url'); $this->load->library(['form_validation', 'session']); $this->load->database(); //load our Register model here $this->load->model('RegisterModel', 'register'); } //registration form page public function index() { //check if the user is already logged in //if yes redirect to the welcome page if ($this->session->userdata('logged_in')) { redirect(base_url() . 'welcome'); } //load the register page views $this->load->view('header'); $this->load->view('register_page'); $this->load->view('footer'); } //register validation and logic public function doRegister() { //set the form validation here $this->form_validation->set_rules('name', 'Name', 'required|min_length[3]'); $this->form_validation->set_message('is_unique', 'Email already exists.'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]'); $this->form_validation->set_rules('password', 'Password', 'required|min_length[4]'); //if the above validation fails, redirect to register page //with vaildation_errors(); if ($this->form_validation->run() == FALSE) { //set the validation errors in flashdata (one time session) $this->session->set_flashdata('errors', validation_errors()); redirect(base_url() . 'register'); } else { //if not get the input values $name = $this->input->post('name'); $email = $this->input->post('email'); $password = sha1($this->input->post('password')); $data = [ 'name' => $name, 'email' => $email, 'password' => $password, 'date_time' => date('Y-m-d H:i:s') ]; //pass the input values to the register model $insert_data = $this->register->add_user($data); //if data inserted then set the success message and redirect to login page if ($insert_data) { $this->session->set_flashdata('msg', 'Successfully Register, Login now!'); redirect(base_url() . 'login'); } } } }
Just read the comments in the above script to understand.
Now before we edit the Welcome.php controller. We are going to create a new controller called MY_Controller in a different folder path.
Path: /codeigniter/application/core
MY_Controller.php
<?php class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('session'); $this->load->helper('url'); $logged_in = $this->session->userdata('logged_in'); if (!$logged_in) { redirect(base_url() . 'login'); } } }
This file we created is to check whether the user is logged in or not, so we don’t have to do this check-in each and every one of our new controllers we are creating.
So lets’ edit the Welcome.php controller.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends MY_Controller { public function index() { $this->load->view('header'); $this->load->view('welcome_message'); $this->load->view('footer'); } }
If you see the above code we have used MY_Controller instead of CI_Controller. So basically we don’t have to do the user login validation in our welcome controller or any other controller.
That’s it, people. Execute the code and see the result yourself.
You can see the demo and also get the files from the download link.
Thank you thank you thank you.
I have been trying this for the last one month without success. Today with your tutorial i have made it
Thank your so much. You saved my life. tons of thnks
Thank you very much indeed good sir
what is the “login” from $this->load->model(‘LoginModel, ‘login’);
It’s a given object name, you can give any name you like instead of using LoginModel everywhere, from the Codeigniter documentation “If you would like your model assigned to a different object name you can specify it via the second parameter of the loading method.”
hi im new to code igniter, im a little bit confused with this line in login_page.php
<form action="register/doRegister” method=”post”> .. do you start to code like this without writing before?
btw thankyou your post enlighten me
without writing before
i dont know why it didnt show up
u saved me a lot of time
can you create that i can access from details of user who logged in in this program itself