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.
Watch the live demo or download code from the link given below
Note : You can also refer the PHPProjectInstall.pdf file given in the download code folder.
Before starting, 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.
Firstly, set base URL in config.php file of CodeIgniter as given below:-
$config['base_url'] = 'http://localhost/login/';
Tutorial Scripts in detail
Below are the details of the code used in this tutorial with proper explanation.
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 IF NOT EXISTS `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,
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 index() {
$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('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(
'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) {
if(isset($this->session->userdata['logged_in'])){
$this->load->view('admin_page');
}else{
$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) {
$username = $this->input->post('username');
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->user_name,
'email' => $result[0]->user_email,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view('admin_page');
}
} 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>
<?php
if (isset($this->session->userdata['logged_in'])) {
header("location: http://localhost/login/index.php/user_authentication/user_login_process");
}
?>
<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>
<hr/>
<?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"/><br /><br />
<label>Password :</label>
<input type="password" name="password" id="password" placeholder="**********"/><br/><br />
<input type="submit" value=" Login " name="submit"/><br />
<a href="<?php echo base_url() ?>index.php/user_authentication/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>
<?php
if (isset($this->session->userdata['logged_in'])) {
header("location: http://localhost/login/index.php/user_authentication/user_login_process");
}
?>
<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>
<hr/>
<?php
echo "<div class='error_msg'>";
echo validation_errors();
echo "</div>";
echo form_open('user_authentication/new_user_registration');
echo form_label('Create Username : ');
echo"<br/>";
echo form_input('username');
echo "<div class='error_msg'>";
if (isset($message_display)) {
echo $message_display;
}
echo "</div>";
echo"<br/>";
echo form_label('Email : ');
echo"<br/>";
$data = array(
'type' => 'email',
'name' => 'email_value'
);
echo form_input($data);
echo"<br/>";
echo"<br/>";
echo form_label('Password : ');
echo"<br/>";
echo form_password('password');
echo"<br/>";
echo"<br/>";
echo form_submit('submit', 'Sign Up');
echo form_close();
?>
<a href="<?php echo base_url() ?> ">For Login Click Here</a>
</div>
</div>
</body>
</html>
Views: admin_page.php
This file load in the admin part, once user is successfully login to admin page.
<html>
<?php
if (isset($this->session->userdata['logged_in'])) {
$username = ($this->session->userdata['logged_in']['username']);
$email = ($this->session->userdata['logged_in']['email']);
} else {
header("location: login");
}
?>
<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>" . $username . "</i> !</b>";
echo "<br/>";
echo "<br/>";
echo "Welcome to Admin Page";
echo "<br/>";
echo "<br/>";
echo "Your Username is " . $username;
echo "<br/>";
echo "Your Email is " . $email;
echo "<br/>";
?>
<b id="logout"><a href="logout">Logout</a></b>
</div>
<br/>
</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($username) {
$condition = "user_name =" . "'" . $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/
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.
50 Replies to “CodeIgniter Simple Login Form With Sessions”
Sir i want to ask you that:
When we use this server at xampp and call view
user_login_process => $this->load->view(‘admin_page’, $data);
Here page is not redirect corectly can u please solve that issue bcz at that view condition admin page did not work correct and and also in url shown like that (http://localhost/login/index.php/user_authentication/user_login_process) instead of (http://localhost/login/index.php/user_authentication/admin)
Please solve for me
Hello Mehboob,
Thanks for looking into it.
We sincerely apologize for this inconvenience. Now, we have updated our codes and it’s reference.
For project installation, download code by giving Download URL and read PHPProjectInstall.pdf
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
and that thing is happen when we click on ligin button please check this on local server clear us
thanks sir for the lesson, keep posting 🙂
followed your codes, but i get a blank page after running: http://localhost/login/index.php/user_authentication/user_login_show. Any help?
you need to change your codeigniter name
When I loaded it to my browser nothing shows. What could be the possible reason?
Sir,
When we use this code .
an error was encoded..
In order to use the Session class you are required to set an encryption key in your config file.
please help me.
Sir, you must open the config file. in config.php. then turn ( $config[‘encryption_key’] = ”; ) into ( $config[‘encryption_key’] = ‘mykey’; ) . it works
Some thoughts.
Why store the password uncrypted in de database?
Why store the password in de session?
You must change in the file user_authentication.php
[line 46]
user_password’ => md5($this->input->post(‘password’))
and
[Line 74]
‘password’ => md5($this->input->post(‘password’))
Hi! I have a problem , I cannot retrieve the data from my session except for the username ,it returns blank value for other data
Hello yen ,
Thanks for sharing your problem with us.
Now, we have updated our codes and it’s reference.
For project installation, download code by giving Download URL and read PHPProjectInstall.pdf
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
Empty page only i see what can i do?
Nice post Thanks You Sir
i follow all your instruction sir but this is what i got:
Not Found
The requested URL /login/index.php/user_authentication/user_login_show was not found on this server.
CAN YOU HELP ME SIR?
Thank you so much 🙂
hello sir,
this is muthuvel .I want codeigniter login form code with registration and forget password program.please send me..i wait for your response..
thank you,
Sir, I got blank page
because there is no data stored to db, check your view and controller
into login_database model, necesary load library database() if cannot valid user.
kuch to kam hai daya.
i want to ask you that:
When we use this server at xampp and call view
user_login_process => $this->load->view(‘admin_page’, $data);
Here page is not redirect corectly can u please solve that issue bcz at that view condition admin page did not work correct and and also in url shown like that (http://localhost/login/index.php/user_authentication/user_login_process) instead of (http://localhost/login/index.php/user_authentication/admin)
hao ho jay nai to
i got error “Call to a member function select() on null”. i already load model. could you help me?
Hello Jauhar
Thanks for sharing your problem with us.
Now, we have updated our codes and it’s reference.
For project installation, download code by giving Download URL and read PHPProjectInstall.pdf
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
hi,
sir validation message is wrong mobile no and date of birth .
Its really usefull tutorial for beigners
hello sir i m new in codeigniter when i submit new_user_registration form then error occur:
Unable to access an error message corresponding to your field name Email.(xss_clean)
pls help me
go to application/config/autoload.php :
$autoload[‘helper’] = array(‘security’);
Or, before your form validation
$this->load->helper(‘security’);
A PHP Error was encountered
Severity: Warning
Message: ini_set(): A session is active. You cannot change the session module’s ini settings at this time
Filename: Session/Session.php
Line Number: 313
Backtrace:
File: D:\xam\htdocs\login\application\controllers\user_authentication.php
Line: 18
Function: library
File: D:\xam\htdocs\login\index.php
Line: 292
Function: require_once
————————————————————————–
A PHP Error was encountered
Severity: Notice
Message: A session had already been started – ignoring session_start()
Filename: Session/Session.php
Line Number: 140
Backtrace:
File: D:\xam\htdocs\login\application\controllers\user_authentication.php
Line: 18
Function: library
File: D:\xam\htdocs\login\index.php
Line: 292
Function: require_once
i got this error. please solve my problem waiting .
I’ve got exactly the same problem… Did you solved it? Anyone can help? Thanks for answering!
Hi diego, do you need code? mail me: [email protected]
Hi, has this problem been solved? I’m currently facing the same problem.
Hi sir,
I did your tutorial I followed all of steps now last step is save css where I can save css files in codeigniter.
A PHP Error was encountered
Severity: Error
Message: Call to undefined function base_url()
Filename: views/login_form.php
Line Number: 12
Backtrace:
load url heiper
in config folder autoload.php
$this->load->helper(‘url’)
Hi
Thank you for the code. I have used it but when I type http://localhost/login/ but I’m getting the following error message
404 Page Not Found
The page you requested was not found.
I have tried to troubeshoot and going line by line but I don’t see reason
Can you please tell what is the url to view registration page and which should be the default controller?
Great post however , I was wanting to know if you could write a litte more on this subject? I be very thankful if you could elaborate a little bit further. Bless you!
Hello Linh,
What you want to know in the script. Do let us know.
Thanks
Pankaj Agarwal
sir i have a problem in storing data in database
now its working perfect.
Can u post the modified code here for this question, as i am facing same issue..
Here page is not redirect corectly can u please solve that issue bcz at that view condition admin page did not work correct and and also in url shown like that (http://localhost/login/index.php/user_authentication/user_login_process) instead of (http://localhost/login/index.php/user_authentication/admin)
Thanks
I the Sign Up Process you write the following:
When you click on singup link, it will redirect you to ‘SignUp.php’ and display a signup form.
what is the signup.php code
I have the perfectly-working code.any one needs, email me.Id:[email protected].
Hi!
I test Your nice code in new Codeigniter 3.0.3 (http://www.codeigniter.com/)
Everything else is working, but Session in this ‘User_authentication.php‘ is not working.
There is different type of configuration in Codeigniter 3.0.3.
Registration is working fine, but I can’t login, because of session problem.
// in Your code load session library = does not work in Codeigniter 3.0.3.
$this->load->library(‘session’);
// I test this also, but no result in ‘autoload.php’
$autoload[‘libraries’] = array(‘database’. ‘session’);
—-
if ($result != false) {
$session_data = array(
‘username’ => $result[0]->user_name,
’email’ => $result[0]->user_email // in Your code there is extra comma
);
// Add user data in session
$this->session->set_userdata(‘logged_in’, $session_data); // debugger give me error information about session in this line
Any help ?
Dear sir,
I cannot display username in Views: admin_page.php.
Can you help me.
Thanks sir!
Thanks it works fine..
If anyone faced 404 page error,Remember you have to add route file.
SO Go to routes.php after you insert all the files as per the instruction above,then you have to just add the below line at the end of route:
$route[‘default_controller’] = ‘user_authentication’;
Then go to config and find encryption key just add this line:
$config[‘encryption_key’] = ‘MAmYvOixfIC0t6PRWPm6cFEDBuJBcOcL’;
Thanks! It works! I have copied each of this code y the sections of CodeIgniter and created the database and I can login and logout.
i get validation messege “Unable to access an error message corresponding to your field name Username.(xss_clean)
Unable to access an error message corresponding to your field name Password.(xss_clean)”
hello sir..
i can’t login or register, every i login or register i have messege from validation “Unable to access an error message corresponding to your field name Username.(xss_clean)” etc..
Please Help Me sir…thank you…