Create a Simple Ajax Login System Using Codeigniter
Hi Friends. Today we will learn how to make Ajax login system in php codeigniter. Here is the step by step tutorial.
Step 1.
Download codeigniter from codeigniter’s website and configure it on local server(www/htdocs).
Step 2.
We are using authentication process so create a mysql table(auth).
[php]
—
— Table structure for table `auth`
—
CREATE TABLE IF NOT EXISTS `auth` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`is_active` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
—
— Dumping data for table `auth`
—
INSERT INTO `auth` (`id`, `username`, `password`, `is_active`) VALUES
(1, ‘admin’, ‘5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8’, 1);
//password is sha1 encrypted
[/php]
Step 3.
Now please update or config database.php file under the directory(application/config/database.php)
[php]
$active_group = ‘default’;
$active_record = TRUE;
$db[‘default’][‘hostname’] = ‘localhost’;
$db[‘default’][‘username’] = ‘root’;
$db[‘default’][‘password’] = ”;
$db[‘default’][‘database’] = ‘your database name’;
$db[‘default’][‘dbdriver’] = ‘mysql’;
$db[‘default’][‘dbprefix’] = ”;
$db[‘default’][‘pconnect’] = TRUE;
$db[‘default’][‘db_debug’] = TRUE;
$db[‘default’][‘cache_on’] = FALSE;
$db[‘default’][‘cachedir’] = ”;
$db[‘default’][‘char_set’] = ‘utf8’;
$db[‘default’][‘dbcollat’] = ‘utf8_general_ci’;
$db[‘default’][‘swap_pre’] = ”;
$db[‘default’][‘autoinit’] = TRUE;
$db[‘default’][‘stricton’] = FALSE;
[/php]
Also setup encryption key in config.php under the directory(application/config/config.php)
[php]
/*
|————————————————————————–
| Encryption Key
|————————————————————————–
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config[‘encryption_key’] = ‘B8BZ72TsJUx15Cqw8F0oB202H7v1fp2N’;
/*
[/php]
Now update autoload.php file under the directory(application/config/autoload.php)
[php]
/*
| ——————————————————————-
| Auto-load Libraries
| ——————————————————————-
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload[‘libraries’] = array(‘database’, ‘session’, ‘xmlrpc’);
*/
$autoload[‘libraries’] = array(‘database’,’form_validation’,’session’);
/*
| ——————————————————————-
| Auto-load Helper Files
| ——————————————————————-
| Prototype:
|
| $autoload[‘helper’] = array(‘url’, ‘file’);
*/
$autoload[‘helper’] = array(‘url’);
[/php]
Step 4.
Create two controller file auth.php and home.php under the directory(application/controller/) and paste following code.
[php]
<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’); //location: application/controller/auth.php class Auth extends CI_Controller { public function __construct() { parent::__construct(); $this->load->Model(‘Auth_model’);
}
public function index()
{
$this->load->view(‘login’);
}
public function logout(){
$this->session->sess_destroy();
redirect(‘/’ ,’refresh’);
exit;
}
public function login(){
$username = $this->input->post(‘username’);
$password = $this->input->post(‘password’);
//call the model for auth
if($this->Auth_model->login($username, $password)){
}
else{
echo’something went wrong’;
}
}
}
/* End of file auth.php */
/* Location: ./application/controllers/auth.php */
[/php]
Next, paste the following code in home.php controller.
[php]
<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’); class Home extends CI_Controller { public function __construct() { parent::__construct(); $this->load->Model(‘Auth_model’);
}
public function index(){
//check user logged in or not
$this->Auth_model->isLoggedIn();
$this->load->view(‘home’);
}
}
/* End of file home.php */
/* Location: ./application/controllers/home.php */
[/php]
Step 5.
Create a model file auth_model.php under the directory(application/models/). And paste following code.
[php]
<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’); //location: application/models/auth_model.php class Auth_model extends CI_Model { public function login($name, $password){ $password = sha1($password); $this->db->where(‘username’,$name);
$this->db->where(‘password’,$password);
$query = $this->db->get(‘auth’);
if($query->num_rows()==1){
foreach ($query->result() as $row){
$data = array(
‘username’=> $row->username,
‘logged_in’=>TRUE
);
}
$this->session->set_userdata($data);
return TRUE;
}
else{
return FALSE;
}
}
public function isLoggedIn(){
header("cache-Control: no-store, no-cache, must-revalidate");
header("cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
$is_logged_in = $this->session->userdata(‘logged_in’);
if(!isset($is_logged_in) || $is_logged_in!==TRUE)
{
redirect(‘/’);
exit;
}
}
}
[/php]
Step 6.
In step 6, create a view file home.php and login.php under the directory(application/views/)
So create login.php file and paste following code.
INVALID USER NAME OR PASSWORD
[code]<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login page</title>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" type="text/css" rel="stylesheet"/>
<style>
#response{display: none}
</style>
</head>
<body>
<div class="container" style="margin-top: 10%">
<blockquote>
<div class="col-md-6 col-md-offset-3">
<h2>Meul Tech : login page</h2>
<a href="https://www.facebook.com/Meul Tech Classes/">by Meul Tech </a>
</div>
<div class="row clear_fix">
<div class="col-md-6 col-md-offset-3">
<style>
#response{display: none}
div #fb, div #gp, div #tw{display: inline-block;}
#fb{width: 180px;}
#gp{width: 100px;}
#tw{width: 180px;}
</style>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.7";
fjs.parentNode.insertBefore(js, fjs);
}(document, ‘script’, ‘facebook-jssdk’));</script>
<div>
<div id="tw">
<a href="https://twitter.com/Meul Tech classes" class="twitter-follow-button" data-show-count="false" data-size="medium">Follow @Meul Tech classes</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?’http’:’https’;if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+’://platform.twitter.com/widgets.js’;fjs.parentNode.insertBefore(js,fjs);}}(document, ‘script’, ‘twitter-wjs’);</script>
</div>
<div id="gp">
<!– Place this tag in your head or just before your close body tag. –>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<!– Place this tag where you want the +1 button to render. –>
<div class="g-plusone" data-href="https://plus.google.com/+Meul Tech ClassesMumbai"></div>
</div>
<div id="fb">
<div class="fb-like" data-href="https://www.facebook.com/Meul Tech Classes/" data-layout="standard" data-action="like" data-size="small" data-show-faces="true" data-share="true"></div>
</div>
</div>
</blockquote>
<br/>
<p class="alert alert-danger" id="response"><b>INVALID USER NAME OR PASSWORD</b></p>
<form id="frm_login" role="form" action="<?php echo base_url(); ?>index.php/auth/login" method="POST">
<div class="form-group">
<label for="">User name</label>
<input type="text" class="form-control" name="username" placeholder="User name">
</div>
<div class="form-group">
<label for="">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<input type="submit" class="btn btn-info btn-block" value="submit">
</form>
</div>
</div>
</div>
<script>
$(document).ready(function (){
$("#frm_login").submit(function (e){
e.preventDefault();
var url = $(this).attr(‘action’);
var method = $(this).attr(‘method’);
var data = $(this).serialize();
$.ajax({
url:url,
type:method,
data:data
}).done(function(data){
if(data !== ”)
{
$("#response").show(‘fast’);
$("#response").effect( "shake" );
$(‘#frm_login’)[0].reset();
}
else
{
window.location.href='<?php echo base_url() ?>index.php/home/’;
throw new Error(‘go’);
}
});
});
$( "div" ).each(function( index ) {
var cl = $(this).attr(‘class’);
if(cl ==”)
{
$(this).hide();
}
});
});
</script>
</body>
</html>
[/code]
$(document).ready(function (){
$(“#frm_login”).submit(function (e){
e.preventDefault();
var url = $(this).attr(‘acti