Monday, February 23, 2015

CodeIgniter Simple Login Form With Sessions

In this tutorial, we are going to learn about creating a simple login form in CodeIgniter. In login form, we made registration module, login module and admin panel using sessions.
We also have a paid ready-to-use advance login & registration module built on CodeIgniter that you can check out at CodeIgniter Login Registration Form.
Creating sessions in CodeIgniter is different from simple PHP. I will give you detailed information about all the method as we move further in this tutorial.
codeigniter-login-form
Before start, let’s have a look on what we are going to learn about.
  • Create login page, signup page and admin page.
  • Setting up validation to all input field.
  • Check for existing users in database during signup process.
  • Check for username and password in database and show their  information stored in database.
  • Create session for admin panel, store users input data in session and destroy session(logout).
We are introducing a flow chart which will give you a clear vision about the objectives of this tutorial.
codeigniter-login-flow-chart

Firstly, set baseurl in config.php  file of CodeIgniter as given below :-
$config['base_url'] = 'http://localhost/login/';

Database Table: user_login

Now create a database name ‘login‘ with a table ‘user_login‘ using the code given below  :-
create database login;
create table user_login(
'id'  int(11) NOT NULL AUTO_INCREMENT,
'user_name'  varchar(255) NOT NULL,
'user_email' varchar(255) NOT NULL,
'user_password'  varchar(255) NOT NULL,
'name'  varchar(255) NOT NULL,
PRIMARY KEY ('id')
);

Controller: user_authentication.php

Before start coding, let’s load all the libraries required to make and manage login form.
First we need to load session and validation libraries in controller file.
So, let’s start coding with controller. Create a file name ‘user_authentication.php‘ in ‘application/controllers’ folder of CodeIgniter. Write the code given below in the file.
<?php

session_start(); //we need to start session in order to access it through CI

Class User_Authentication extends CI_Controller {

public function __construct() {
parent::__construct();

// Load form helper library
$this->load->helper('form');

// Load form validation library
$this->load->library('form_validation');

// Load session library
$this->load->library('session');

// Load database
$this->load->model('login_database');

}

// Show login page
public function user_login_show() {
$this->load->view('login_form');
}

// Show registration page
public function user_registration_show() {
$this->load->view('registration_form');
}

// Validate and store registration data in database
public function new_user_registration() {

// Check validation for user input in SignUp form
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('registration_form');
} else {
$data = array(
'name' => $this->input->post('name'),
'user_name' => $this->input->post('username'),
'user_email' => $this->input->post('email_value'),
'user_password' => $this->input->post('password')
);
$result = $this->login_database->registration_insert($data) ;
if ($result == TRUE) {
$data['message_display'] = 'Registration Successfully !';
$this->load->view('login_form', $data);
} else {
$data['message_display'] = 'Username already exist!';
$this->load->view('registration_form', $data);
}
}
}

// Check for user login process
public function user_login_process() {

$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);

// Add user data in session
$this->session->set_userdata('logged_in', $sess_array);
$result = $this->login_database->read_user_information($sess_array);
if($result != false){
$data = array(
'name' =>$result[0]->name,
'username' =>$result[0]->user_name,
'email' =>$result[0]->user_email,
'password' =>$result[0]->user_password
);
$this->load->view('admin_page', $data);
}
}else{
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}

// Logout from admin page
public function logout() {

// Removing session data
$sess_array = array(
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('login_form', $data);
}
}

?>

Views: login_form.php

This will show login form on the view page.
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<?php
if (isset($logout_message)) {
echo "<div class='message'>";
echo $logout_message;
echo "</div>";
}
?>
<?php
if (isset($message_display)) {
echo "<div class='message'>";
echo $message_display;
echo "</div>";
}
?>
<div id="main">
<div id="login">
<h2>Login Form</h2>
<?php echo form_open('user_authentication/user_login_process'); ?>
<?php
echo "<div class='error_msg'>";
if (isset($error_message)) {
echo $error_message;
}
echo validation_errors();
echo "</div>";
?>
<label>UserName :</label>
<input type="text" name="username" id="name" placeholder="username"/>
<label>Password :</label>
<input type="password" name="password" id="password" placeholder="**********"/>
<input type="submit" value=" Login " name="submit"/>
<a href="user_registration_show">To SignUp Click Here</a>
<?php echo form_close(); ?>
</div>
</div>
</body>
</html>

Views: registration_form.php

This file will load to show signup form.
<html>
<head>
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="main">
<div id="login">
<h2>Registration Form</h2>
<?php
echo "<div class='error_msg'>";
echo validation_errors();
echo "</div>";
echo form_open('user_authentication/new_user_registration');
echo form_label('Name : ');
echo form_input('name');
echo form_label('Create Username : ');
echo form_input('username');
echo "<div class='error_msg'>";
if (isset($message_display)) {
echo $message_display;
}
echo "</div>";
echo form_label('Email : ');
$data = array(
'type' => 'email',
'name' => 'email_value'
);
echo form_input($data);
echo form_label('Password : ');
echo form_password('password');
echo form_submit('submit', 'Sign Up');
echo form_close();
?>
</div>
</div>
</body>
</html>

Views: admin_page.php

This file load in the admin part, once user is successfully login to admin page.
<html>
<head>
<title>Admin Page</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="profile">
<?php
echo "Hello <b id='welcome'><i>" . $name . "</i> !</b>";
echo "Welcome to Admin Page";
echo "Your Username is " . $username;
echo "Your Email is " . $email;
echo "Your Password is " . $password;
?>
<b id="logout"><a href="logout">Logout</a></b>
</div>
</body>
</html>

Models : login_database.php

When a new user register.It check for duplicate user registration.
<?php

Class Login_Database extends CI_Model {

// Insert registration data in database
public function registration_insert($data) {

// Query to check whether username already exist or not
$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {

// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}

// Read data using username and password
public function login($data) {

$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}

// Read data from database to show data in admin page
public function read_user_information($sess_array) {

$condition = "user_name =" . "'" . $sess_array['username'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();

if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}

}

?>

CSS : style.css

Design for login, admin and registration page.
#main{
width:960px;
margin:50px auto;
font-family:raleway;
}

span{
color:red;
}

h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 30px;
}

#login{

width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: 70px;
}

input[type=text],input[type=password], input[type=email]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}

input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}

#profile{
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7;
}

#logout{
float:right;
padding:5px;
border:dashed 1px gray;
margin-top: -168px;
}

a{
text-decoration:none;
color: cornflowerblue;
}

i{
color: cornflowerblue;
}

.error_msg{
color:red;
font-size: 16px;
}

.message{
position: absolute;
font-weight: bold;
font-size: 28px;
color: #6495ED;
left: 262px;
width: 500px;
text-align: center;
}

Process:-

First of all it is needed to type  the given below URL in browser.
http://localhost/login/index.php/user_authentication/user_login_show
When browser get the above url it will display a login page. This page contains a login section and a signup link.
The whole process includes :-
  • SignUp process and
  • SignIn process
So, let’s learn about these processes.
Sign Up Process :-
When you click on singup link, it will redirect you to ‘SignUp.php’ and display a signup form.
After filling all input field when you click on submit button, all data travels to new_user_registration() function of controller. This function first check validation for each field.
If your data is empty or invalid then it will generate an error message but, if all input field get proper data then it will connect you to database.
Before inserting data to database, it first check for username in database.
If given username is already available in database, a ‘username already exits ! ‘ message will be displayed but if username is not available in database then it will insert all the information in the database and display a ‘SignUp Successfullly !’ message.

Sign In Process :-
After signup, you can login by giving a valid username and password. If invalid username  or password will be given then a error message will be displayed.
Now let’s have a look at the whole procedure of SignIn. When you enters username and password, the values are travelled to  user_login_process() function in controller where the validation for each field is checked.
When all input given are valid then user_login_process()  function matches the  given username and  password with data stored in database.
If match doesn’t found then you will be redirected to login page and an error message will be displayed. But, if match found in database then session will be created and user data will be inserted into session data.
Now, these data are send to admin page where all information along with logout option will be displayed. When you will click on logout then logout() function will be called and where session data will be destroyed. After this, you will be redirect to login page for a new login.

Conclusion :

Thanks for reading the complete post. Hope you have enjoyed reading this blog post and got the concept. You can share your views in the space provided below and get in touch with us.

0 comments:

Post a Comment

Labels

.htaccess (5) 2step verification in php (1) 404 Page (1) Address Autocomplete (1) Admin (1) Ajax (3) alias key generation (1) All Browsers Testing (1) Android (19) Android 5.0 (2) Android Life Cycle (1) Android webview media capture (1) angular js (7) Angular Js ebook (1) AngularJS (23) Apache and mysql start up automatically once system boot (1) array_combine() (1) array_merge() (1) array_search() (1) async css and js (1) auto generate url slug in codeginiter (1) Auto reload (1) Autocomplete (1) automation code for php and mysql (1) AWS (1) AWS EC2 Hosting (6) AWS EC2 Hosting Connect with notepad++ (1) AWS ECS Hosting (1) base_url() (1) Basic php example on this keyword use (1) Best Practices to write jquery (1) Bootstrap (2) Bootstrap form tag problem (1) Bootstrap Modal (1) Bootstrap Modals (1) Breadcrumb (1) Broad band usage meter (1) Can't connect to MySQL server on (1) Cannot retrieve metalink for repository (1) Career Guidance (1) Carousel (1) Categories of websites (1) Cent OS (2) CI (1) Ci Errors (1) ckeditor (3) Clear Browser Cache Trick (1) Client IP Address (1) Code completion for codeigniter (1) Codehint for CodeIgniter (1) CodeIgniter (54) Codeigniter Controllers (1) Codeigniter email (1) Codeigniter file upload (2) Codeigniter send grid integration (1) CodeIgniter with Dreamweaver (1) Codigniter4 (1) color replace function in jquery (1) colorReplace function (1) configuration files locations (1) Controllers in controllers angular js (1) Cookies (1) core php file upload (1) count down timer in seconds in jquery (1) Countries Table in mysql (1) Create User in mysql Db (1) CryptoJS (1) CSS (3) CSS tricks (2) curl parallel calls (1) Currency API (1) Customize date format in php (1) Data dictionary (1) data of birth validation and generation codeigniter (1) Database backup in php (1) date (1) Date Difference (2) date difference in jquery (1) Date format in php (1) Date functions (1) datepicker date format jquery (1) Datetime Picker (1) datewise mysql backup (1) DBFunctions (1) Default Image in html (1) Desktop tricks (1) Detect Android Mobile (1) Detect Iphone using javascript (1) Disadvantages of Joomla (1) Disadvantages of Wordpress (1) Distance Calculation (1) document printing (1) Document submit (1) dreamweaver (1) Drupal CMS (2) Drupal Components (1) Drupal Update (1) Dynamic jQuery (21) Dynamic websites building (1) echo (1) editor for html interface (1) Email (2) Email extract in php (1) email php configuration (1) empty() and is_null() difference (1) error handling in php (1) event.PreventDefault() (1) execution time in javascript (1) extract numbers php (1) Facebook Link Posting (1) Facebook Login Error Javascript (1) Facebook Page Likes (1) Fancybox (1) Fastpanel (1) Features of Joomla (1) Features of Wordpress (1) file upload (1) File upload in jquery (1) File upload through URL with php script (1) file_get_contents (1) Files listing from folders in php (1) FileUpload (2) fileupload in jquery with preview (1) filezilla (1) Filter to top (1) Find the Framework of a website (1) Firewall Configuration in Centos (1) FOR php developers (2) Form_validation form with codeigniter (1) FTP (1) Full calendar (1) Geo API (4) Geo Code (2) Geo complete (1) Geo Location (1) GeoLocation (4) get ipaddress (1) gmail contacts api (1) Google Chrome Install (1) Google Map (1) Google Maps (9) Grant all privileges in mysql db (1) Grocery Crud (5) Guess CMS (1) hashtag (1) History Clear (1) HMVC (1) Host is not allowed to connect to MySQL Server (1) how to include header and footer html in html (1) How to prevent sql injection in php (1) how to zip file in linux (1) HTML (4) HTML CSS JS compression (1) HTML Typography (1) HTML5 (4) httpd.conf Configurations (1) Huge IT Silder (1) Hybrid App (1) Hyperlinks (1) image resize in codeigniter (1) Image with preview and remove html (1) Include() and include_once Difference (2) India States (1) Interfaces in PHP (1) Internal server error solution (1) Invoice Templates (1) ionic (13) ionic ios (1) iOS (3) iTunes (1) Javascript (45) javascript countdown timer (1) javascript email validation (1) Javascript Object properties view (1) Javascript UNIX time stamp converter (1) jmeter (3) Jquery (40) jquery datepicker (2) jquery detect idle state (1) jquery list sort (1) Jquery OWL Carousel (1) Jquery UI (1) jquery username validation (1) jquery validation (1) JS (1) JSON (3) Laravel (4) Laravel Tutorials (2) Latest Android Version (1) Linux commands (5) LINUX Ftp Configuration (1) Linux Server IP Address (1) List Sortable in Jquery UI (1) Lollipop (1) Magento (1) mail in php (1) main controller and child controller and another child controller (1) maximum execution time in php code (1) Media Capture in HTML5 (1) method overloading in php (1) method overriding in php (1) mod_rewrite (1) Mouse Deselection Javascript (1) Multidimensinal Array sort (1) multiple comparisons in php (1) Multiple file upload in Angular JS (1) Multiple file upload in jquery (1) multiple file upload in php (1) multiselect (1) Mysql (21) mysql and apache start up automatically once system boot (1) mysql connect (1) mysql connect in windows os (1) mysql database backup (1) mysql datatypes (1) Mysql DB (1) mysql Db connection program (1) Mysql Errors (1) mysql functions (1) MySQL HostName (1) mysql query tricks (1) MySQL server at 'reading initial communication packet' (1) mysql_real_escape_string() (1) mysql_secure_installation (1) mysql.sock (2) Error (1) mysqli (2) Native App (1) Netbeans for linux (1) Network usage monitor (1) ng-bind (1) ng-click (1) Node js (1) Notepad++ (1) onchange display images (1) Online UNIX Timestamp to human readble format converter (1) OOPS in php (1) Pagination in Codeigniter (1) Pagination in php (1) Password encryption and decryption in php (1) Paypal (1) PayU Form (1) PDF (1) PDO (2) Pendrive Data Recovery (1) php (62) PHP 5.4.0 (2) php abstract class example (1) PHP ajax file upload (2) PHP ajax request detection (1) PHP Basic Login and logout (1) PHP Codeigniter database backup code (1) PHP Contact us email form code (1) PHP corn jobs (1) php database backup script (1) php email validation (1) PHP Environment Setup (1) PHP Errors (1) PHP Extension and Application Repository) (1) php file upload (1) PHP File Uploading (1) PHP fileupload helper in codeigniter (1) PHP interview questions (4) PHP lamda functions examples (1) PHP Login (1) PHP pdo (1) PHP PDO script to insert data inside mysql db (1) PHP Random Password generation Script (2) php script execution limit (1) php script to display months (1) php script to print years as dropdown (1) PHP Storm (2) PHP Storm license key (1) PHP strong encryption and decryption (1) php timeslot generator (1) php-mysql Modules (1) phpmyadmin (2) phpMyAdmin install (1) Pin-code finder (1) Pincode (1) Play youtube video in angular JS (1) Popup (2) POPUP in javascript (1) POST and GET Difference (1) POST DATA IN PHP (1) Postfix sendmail (1) preview of selected file (1) Print content with jquery (1) print() (1) Push Notifications (1) query string based pagination in codeigniter (1) Random key (1) ratings (1) regular expressions (1) remote validation (1) remove query string (1) Remove Sale Tag or Logo of woocommerce (1) Repository (1) require_once() (1) require() (1) Resize Image Dynamically (1) result_array() (1) rpmdb open fail (1) Salaries (1) SCP Command syntax (1) select images display in webbrowser (1) Selected values in javascript (1) Send free sms (1) Send Grid (1) Send Grid Email integration (1) SEO PHP (1) Session Management in PHP (1) show active class in the url automatically php (1) Show alternate image (1) simple ajax php script (1) Simple Login in PHP (1) Simple registraion (1) single file upload (1) site2sms script (1) Slideshow (1) SMTP Configuration (2) SOFTWARE TECHNOLOGY TIPS (1) Sort list items by Mouse in jquery (1) sprintf in php (1) SQL Injection in php (1) States Countries API (1) static variable in javascript (1) store date in php (1) stripslashes() (1) strtotime (1) sum of array values (1) sumo select (1) system error: 113 (1) Talk To Camera (1) Text to ASCII Generator (1) this keyword (1) Time ago function in javascript (1) Time ago Plugin (1) Time in PHP (1) time picker in grocery crud admin (1) Timeslot Generation in PHP (1) Tooltips using css (1) trigger in mysql (1) ubuntu (1) UNIX timestamp to HUMan readable converter (1) use full tutorials (1) user ur domain inseted of localhost (1) validation in javascript (1) Version Controls for PHP (1) Webmin (1) What CMS (1) Why Drupal CMS (1) Windows 10 (1) Windows Commands (1) Wordpress (2) Xampp (2) Xampp Localhost (1) Xampp Security (1) Yii Framework configuration (1) Yii framework installation (1) ZipArchive (1) ZipArchive php aws (1)
 
TOP