The session is not working properly. when login, it is directing member_area function which is correct but in member_area function if the condition is not working. The result is directly going in else part of member_area function that is output dies. Is there any mistake in member_area function if condition?
This is my main controller i.e., Welcome controller
function login()
{
$this->form_validation->set_rules('email', 'E-mail', 'valid_email');
$this->form_validation->set_rules('password', 'Password', 'min_length[5]|max_length[8]');
if ($this->form_validation->run()==FALSE)
{
$data['view'] = 'login_view';
$this->load->view('load_view',$data);
}
else
{
$email=$_POST['email'];
$password = md5($_POST['password']);
$this->load->model('Sample_model');
$credentials = array(
'email' => $_POST['email'],
'password' => md5($_POST['password'])
);
$user = $this->Sample_model->check_user($credentials);
if($user->num_rows() == 1)
{
$user = $user->row();
$session = array(
'name' => $user->name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($sesson);
redirect('welcome/member_area');
}
else {
$data['view'] = 'error_view';
$data['msg'] = 'Login failed';
$this->load->view('load_view',$data);
}
}
}
public function member_area()
{
if($this->session->userdata('is_logged_in'))
{
$data['view'] = 'memberarea_view';
$this->load->view('load_view',$data);
}
else die('die');
}
I have added session in config/Autoload
$autoload['libraries'] = array('database','session','form_validation');
This is the model used in the present login.
Sample_model
<?php
class Sample_model extends CI_Model {
public function __construct()
{
//Call the CI_Model constructor
parent::__construct();
}
public function add_user($user)
{
return $this->db->insert('users', $user);
}
public function check_user($credentials)
{
$this->db->where($credentials);
return $this->db->get('users');
}
}
This is login_view form. I am entering email and password from this form.
<section class="title">
<div class="container">
<div class="row-fluid">
<div class="span6">
<h1>Login</h1>
</div>
<div class="span6">
<ul class="breadcrumb pull-right">
<li>Home <span class="divider">/</span></li>
<li>Pages <span class="divider">/</span></li>
<li class="active">Login</li>
</ul>
</div>
</div>
</div>
</section>
<!-- / .title -->
<section id="login-page" class="container">
<form class="center" action='' method="POST">
<fieldset class="login-form">
<div class="control-group">
<!-- E-mail -->
<div class="controls">
<input type="text" id="email" name="email" placeholder="E-mail" class="input-xlarge" required="required">
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group">
<!-- Password-->
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password" class="input-xlarge" required="required">
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success btn-large btn-block">Login</button>
</div>
</div>
</fieldset>
</form>
</section>
<!-- /#login-page -->
Libraries
$autoload['libraries'] = array('database','session','form_validation');
helper
$autoload['helper'] = array('url', 'file');
Controller
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
function login()
{
$this->form_validation->set_rules('email', 'E-mail', 'valid_email');
$this->form_validation->set_rules('password', 'Password', 'min_length[5]|max_length[8]');
if ($this->form_validation->run()==FALSE)
{
$data['view'] = 'login_view';
$this->load->view('login_view',$data);
}
else
{
$email=$_POST['email'];
$password = md5($_POST['password']);
$this->load->model('Sample_model');
$credentials = array(
'email' => $_POST['email'],
'password' => md5($_POST['password'])
);
$user = $this->Sample_model->check_user($credentials);
if($user->num_rows() == 1)
{
$user = $user->row();
$session = array(
'name' => $user->name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($session);
redirect('welcome/member_area');
}
else {
$data['view'] = 'error_view';
$data['msg'] = 'Login failed';
$this->load->view('login_view',$data);
}
}
}
public function member_area()
{
if($this->session->userdata('is_logged_in'))
{
$data['view'] = 'member_view';
$this->load->view('member_view',$data);
}
else{ die('die');
}
}
function logout()
{
$newdata = array(
'name' =>'',
'is_logged_in' => FALSE,
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
redirect('welcome/login','refresh');
}
}
Model
class Sample_model extends CI_Model {
public function __construct()
{
//Call the CI_Model constructor
parent::__construct();
}
public function add_user($user)
{
return $this->db->insert('users', $user);
}
public function check_user($credentials)
{
$this->db->where($credentials);
return $this->db->get('users');
}
}
Login View
<div class="control-group">
<!-- E-mail -->
<div class="controls">
<input type="text" id="email" name="email" placeholder="E-mail" class="input-xlarge" required="required">
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group">
<!-- Password-->
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password" class="input-xlarge" required="required">
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success btn-large btn-block">Login</button>
</div>
</div>
</fieldset></form></section>
Member View
Welcome Member
Related
I have already created a login and registration system in my website. I have a table in my database where all the user information is stored called 'users'.I searched a lot but could not get much far.
My class
public function change_password()
{
$this->load->view('templates/header');
$this->load->view('registration/changepassword');
$this->load->view('templates/footer');
}
public function change()
{
$this->form_validation->set_rules('newpassword', 'New Password', 'required|matches[rpassword]');
$this->form_validation->set_rules('rpassword', 'Retype Password', 'required');
if ($this->form_validation->run() == FALSE) {
redirect('registration/change_password');
}else{
$query = $this->Login_Database->checkOldPass(sha1($this->input->post('oldpassword')));
if($query){
$query = $this->Login_Database->saveNewPass(sha1($this->input->post('newpassword')));
if($query){
redirect('registration/change_password');
}else{
redirect('registration/change_password');
}
}
redirect('');
}
}
My model
// Insert registration data in database
public function checkOldPass($old_password)
{
$this->db->select('*');
$this->db->from('users');
$this->db->select('id');
$this->db->where('id', 'id');
$this->db->where('password', $this->input->post('oldpassword'));
$query = $this->db->get();
if ($query->num_rows > 0) {
return true;
} else {
$this->form_validation->set_message('checkOldPassword', 'wrong old password.');
return false;
}
}
public function saveNewPass($new_pass)
{
$data = array(
'password' => $new_pass
);
$this->db->where('id', 'id');
$this->db->update('users', $data);
return true;
}
}
My form
<h1><p class="text-center" style="font-family: 'Passion One',
cursive;">Change Password</p></h1>
<div>
<form class="form-horizontal" method="post"
action="<?php echo base_url() ?>Registration/change">
<fieldset>
<br>
<div class="form-group">
<label class="col-md-4 control-label" for="phone">Old
Password</label>
<div class="col-md-4">
<input id="oldpassword" name="oldpassword" type="password"
placeholder="Old Password"
class="form-control input-md"
required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="phone">New
Password</label>
<div class="col-md-4">
<input id="newpassword" name="newpassword" type="password"
placeholder="New Password"
class="form-control input-md"
required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="phone">Conform
Password</label>
<div class="col-md-4">
<input id="rpassword" name="rpassword" type="password"
placeholder="Retype Password"
class="form-control input-md"
required="">
</div>
</div>
<br>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-4 control-label" for="save"></label>
<div class="col-md-8">
<button type="submit" class="btn btn-success">Save</button>
<a id="cancel" name="cancel" class="btn btn-danger" href="<?
php echo base_url(); ?>">
Cancel</a><br><br>
</div>
<br><br><br>
</fieldset>
</form>
</div>
My class is inside a class called Registration.Any help would be much appreciated. Also the name of my model is 'Login_Database.php' and the name of my form is 'changepassword.php'
Please use below code in controller and your model. if you have any problem please reply me.
// controller function
public function change(){
if ($this->form_validation->run('update_password') == True)
{
$old_password = sha1($_POST['oldpassword']);
unset($_POST['oldpassword']);
$post = $this->input->post();
$status = $this->model_name->check_old_password($old_password, $user_id); //check old password
if($status==true){
if($_POST['newpassword']==$_POST['rpassword']){
if($this->model_name->update_password($post, $user_id)){
$this->session->set_flashdata('message_success', "Password update successully.");
redirect('registration/change_password');
}else{
$this->session->set_flashdata('article_failed', "Password not update successully.");
redirect('registration/change_password');
}
}else{
$this->session->set_flashdata('article_failed', "Sorry your new password and confirm password does not matched.");
redirect('registration/change_password');
}
}
}else{
$this->session->set_flashdata('article_failed', "Sorry your old password is wrong.");
redirect('registration/change_password');
}
}
// model function
public function check_old_password($old_password, $user_id){
$query = $this->db->select('id')
->from('users')
->where(['id'=>$user_id, 'password'=>$old_password])
->get()
->row();
if($query>0){
return TURE;
}else{
return FALSE;
}
}
public function update_password($post, $user_id){
$password = sh1($post['newpassword']);
return $this->db->where('id', $user_id)
->update('users', ['password'=>$password]);
}
The problem is when i have login to system and in home, i try to refresh the page but then i go to the login page again and not stay in home, even though i have login. can you help me ?
This is my model (m_sisip.php)
function login($username, $password)
{
$query = $this->db->select('*')
->from('TBL_USER')
->where('USERNAME', $username)
->where('PASSWORD', $password)
->get();
if($query->num_rows()==1){
return $query->result();
}
else{
return false;
}
}
This is my controller (verifylogin.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('m_sisip','',TRUE);
$this->load->helper(array('form','html'));
$this->load->library(array('form_validation','session','security'));
}
function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$data['base_url'] = $this->config->item('base_url');
$this->load->view('login',$data);
}
else
{
redirect('c_ta/index', 'refresh');
}
}
function check_database($password)
{
$username = $this->input->post('username');
$username = $this->security->xss_clean($username);
$password = $this->input->post('password');
$password = $this->security->xss_clean($password);
$result = $this->m_sisip->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $rows)
{
$newdata = array(
'id_user' => $rows->ID_USER,
'id_role' => $rows->ID_ROLE,
'username' => $rows->USERNAME,
'password' => $rows->PASSWORD,
'nama_user' => $rows->NAMA_USER,
'jenis_kelamin'=> $rows->JENIS_KELAMIN,
'alamat_user' => $rows->ALAMAT_USER,
'notelp_user' => $rows->NOTELP_USER,
'email_user' => $rows->EMAIL_USER,
'foto_user' => $rows->FOTO_USER,
'is_deleted' => $rows->IS_DELETED,
'logged_in' => true
);
}
$this->session->set_userdata($newdata);
return true;
}
else
{
$this->form_validation->set_message('check_database', 'invalid username or password');
return false;
}
}
}
?>
And this is my view (login.php)
<form action="<?php echo site_url('verifylogin');?>"method="POST">
<fieldset>
<label class="block clearfix">
<span class="block input-icon input-icon-right">
<input type="text" id="username" name="username" class="form-control" placeholder="Username" />
<i class="ace-icon fa fa-user"></i>
</span>
</label>
<label class="block clearfix">
<span class="block input-icon input-icon-right">
<input type="password" id="password" name="password" class="form-control" placeholder="Password" />
<i class="ace-icon fa fa-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<div class="text-center">
<button type="submit" class="width-35 pull-justify btn btn-sm btn-danger">
<i class="ace-icon fa fa-key"></i>
<span class="bigger-110">Login</span>
</button>
</div>
</div>
<div class="space-4"></div>
</fieldset>
</form>
This my model page where I make database connectivity. Registration from working fine but login form not working. Even don't show any message too. I not good in codeigniter. Please let me know where is wrong.
Below is my code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
if($this->session->userdata('user_name')!="")
{
$this->welcome();
}
else
{
$data['title']= 'Home';
$this->load->view("index.php", $data);
}
}
function welcome()
{
$data['title']= 'Welcome';
$this->load->view('header_view',$data);
$this->load->view('welcome_view.php', $data);
$this->load->view('footer_view',$data);
}
public function login()
{
alert("gregrtg");
$email=$this->input->get('email');
$password=$this->input->get('password');
$result=$this->user_model->login($email,$password);
$data['title']= 'Register successfully!';
//if($result)
//$input = '/application/views/vendor-profile.php'; // you can't access view directly. call this view from a controller.
// echo json_encode(array("next_url"=>$input));
if($result) $this->load->view("vendor-profile.php",$data);
else $this->index();
}
function thank()
{
$this->user_model->add_user();
$data['title']= 'Register successfully!';
$this->load->view("index.php", $data);
}
public function registration()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean|callback_check_user_ci');
$this->form_validation->set_rules('user_mobile','User Mobile','trim|required|min_lenght[10]|max_length[10]');
$this->form_validation->set_rules('email_address', 'Your Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$this->user_model->add_user();
$data['title']= 'Register successfully!';
$this->thank();
}
}
public function logout()
{
$newdata = array(
'user_id' =>'',
'user_name' =>'',
'user_email' => '',
'logged_in' => FALSE,
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
$this->index();
}
public function check_user_ci()
{
$usr=$this->input->post('user_name');
$result=$this->user_model->check_user_exist($usr);
if($result)
{
$this->form_validation->set_message('check_user', 'User Name already exit.');
return false;
}
else
{
return true;
}
}
public function check_user()
{
$usr=$this->input->post('name');
$result=$this->user_model->check_user_exist($usr);
if($result)
{
echo "false";
}
else{
echo "true";
}
}
}
?>
this is my controller file....
<!-- Modal Popup Sign Up and Login Start Here -->
<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Sign Up / Login</h4>
</div>
<!-- Tab Start Here -->
<div role="tabpanel">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><span class="commom-icon signup"></span> Sign Up</li>
<li role="presentation"><span class="commom-icon login"></span> Log In</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="signup">
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open("user/thank"); ?>
<div class="signUpForm">
<div class="form-group" id="title1">
<?php echo $title; ?>
</div>
</div>
<div class="signUpForm">
<div class="form-group">
<label for="inputText">Enter Name</label>
<input type="text" class="form-control" placeholder="Enter Name" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" /><div id="usr_verify" class="verify" style="display:none;"> Invalid User</div>
<div id="usr_verify1" class="verify" style="display:none;">User Field should not be empty!</div>
</div>
<div class="form-group">
<label for="inputText">Enter Mobile No.</label>
<input type="text" id="mobile_number" class="form-control" placeholder="Enter Mobile No." name="mobile_number" value="<?php echo set_value('mobile_number'); ?>" /><span id="mobile_verify" class="verify" style="display:none;">Invalid Mobile Number</span><span id="mobile_verify1" class="verify" style="display:none;"> Mobile number should not be Empty</span>
</div>
<div class="form-group">
<label for="inputText">Enter Email</label>
<input type="text" id="email_address" class="form-control" placeholder="Enter Mobile No." name="email_address" value="<?php echo set_value('email_address'); ?>" /><span id="email_verify" class="verify"style="display:none;">Invalid EmailID</span><span id="email_verify1" class="verify" style="display:none;"> EmailID should not be Empty</span>
</div>
<div class="form-group">
<label for="inputPassword">Password:</label>
<input type="password" id="password" class="form-control" placeholder="Enter Password" name="password" value="<?php echo set_value('password'); ?>" /><span id="password_verify" class="verify" style="display:none;">Password Should not be empty</span>
</div>
<div class="form-group">
<label for="inputPassword">Confirm Password:</label>
<input type="password" id="con_password" class="form-control" placeholder="Enter Confirm Password" name="con_password" value="<?php echo set_value('con_password'); ?>" /><span id="confrimpwd_verify" class="verify" style="display:none;">Confirm Password Should not be empty!</span>
<span id="confrimpwd_verify1" class="verify" style="display:none;">Confirm Password and password not matching!</span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12" align="right">
<input type="button" id="formsubmit" class="greenButton" value="Submit" />
<!-- <button type="submit" class="btn btn-danger">Submit</button>-->
</div>
</div>
<?php echo form_close(); ?>
</div>
<div role="tabpanel" class="tab-pane" id="login">
<?php echo form_open("user/login");?>
<div class="loginForm">
<div class="form-group" id="myDiv">
<?php echo $title;?>
</div>
<div class="form-group">
<label for="exampleInputEmail1"> Email address</label>
<input type="email" class="form-control" id="useremail" placeholder="Enter email" value="<?php echo set_value('username'); ?>">
</div>
<div id="emailerror" style="display:none;">Email Field is required!</div>
<div class="form-group">
<label for="exampleInputPassword1"> Password</label>
<input type="password" class="form-control" id="userpassword" placeholder="Password" value="<?php echo set_value('userpassword'); ?>">
</div>
<div id="passworderror" style="display:none;">Password field is required!</div>
<div class="row">
<div class="col-xs-6 mb20 forgetBtn" align="left"> <span class="label label-warning cp">Forget Password ! ! !</span> </div>
<div class="col-xs-6" align="right">
<input type="button" class="btn btn-danger" id="check" value="Login">
</div>
</div>
</div>
<div id="div1"></div>
<?php echo form_close(); ?>
<form>
<div class="fgtForm hide">
<div class="form-group">
<label for="exampleInputEmail1"> Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" required>
</div>
<div class="row">
<div class="col-xs-6 mb20 backLoginBtn" align="left"> <span class="label label-warning cp">Back to Login</span> </div>
<div class="col-xs-6" align="right">
<input type="button" class="greenButton" value="Submit" onclick="validate()" />
<!--<button type="submit" class="btn btn-danger">Click To Process</button>-->
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- Tab End Her -->
</div>
</div>
</div>
<!-- Modal Popup Sign Up and Login End Here -->
<script type="text/javascript">
$("#formsubmit").click(function(){
var oxmlHttpSend;
if($("#user_name").val().length == 0)
{
$("#usr_verify1").show();
}
var mobile=$("#mobile_number").val();
var phoneno = /^\d{10}$/;
if(mobile!="")
{
if(mobile.match(phoneno))
{
$("#mobile_verify").hide();
$("#mobile_verify1").hide();
}
else
{
$("#mobile_verify").show();
$("#mobile_verify1").hide();
}
}
else
{
$("#mobile_verify1").show();
$("#mobile_verify").hide();
}
var email = $("#email_address").val();
if(email!="")
{
var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)#([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
if(!regex.test(email))
{
$("#email_verify").show();
$("#email_verify1").hide();
}
else{
$("#email_verify").hide();
}
}
else
{
$("#email_verify1").show();
$("#email_verify").hide();
}
var password=$("#password").val();
if(password=="")
{
$("#password_verify").show();
}
else
{
$("#password_verify").hide();
}
var con_password=$("#con_password").val();
if(con_password=="")
{
$("#confrimpwd_verify").show();
}
else
{
$("#confrimpwd_verify").hide();
}
if(password!=con_password)
{
$("#confrimpwd_verify1").show();
}
else
{
$("#confrimpwd_verify1").hide();
}
if(typeof XMLHttpRequest != "undefined")
{
oxmlHttpSend = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
}
if(oxmlHttpSend == null)
{
alert("Browser does not support XML Http Request");
return;
}
var url = "<?php echo base_url();?>index.php/user/thank";
url += "?name=" + $("#user_name").val() + "&mobile=" + $("#mobile_number").val() +"&email=" + $("#email_address").val() +"&password=" + $("#password").val();
oxmlHttpSend.open("GET",url,true);
oxmlHttpSend.send(url);
});
</script>
<script >
$("#check").click(function()
{
var df1=$("#useremail").val();
var df2=$("#userpassword").val();
if(df1=="")
{
$("#emailerror").show();
$("#passworderror").hide();
}
if(df2=="")
{
$("#emailerror").hide();
$("#passworderror").show();
}
if(df1=="" && df2=="")
{
$("#emailerror").show();
$("#passworderror").show();
}
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
url="<?php echo base_url();?>index.php/user/login";
url+="?email= "+$("#useremail").val()+"&password= "+$("#userpassword").val();
xmlhttp.open("GET",url,true);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
</script>
main view page where login form is not working
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function login($email,$password)
{
$this->db->where("email",$email);
$this->db->where("password",$password);
$query=$this->db->get("user");
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'user_id' => $rows->id,
'user_name' => $rows->username,
'user_mobile' => $rows->mobile,
'user_email' => $rows->email,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
public function add_user()
{
$this->db->where("email",$this->input->get('email'));
$query=$this->db->get("user");
if($query->num_rows()>0)
{
return true;
}
else
{
$data=array(
'username'=>$this->input->get('name'),
'mobile'=>$this->input->get('mobile'),
'email'=>$this->input->get('email'),
'password'=>md5($this->input->get('password'))
);
$this->db->where("username",$data['username']);
$query=$this->db->get("user");
$result=$this->db->insert('user',$data);
if($result->num_rows()>0)
{
return true;
}
else
{
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
}
}
public function check_user_exist($usr)
{
$this->db->where("username",$usr);
$query=$this->db->get("user");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
}
?>
alert("gregrtg"); is a function for JavaScript and not for PHP.
how to flash error on view in codeigniter.... i m creating login on
codeigniter but if user login value not equivalent to dataase table
value. then i need to show error ....invalid user name or
password.. for that i m using set_flashdata but.... on view when i
call that by error_message(). then error showing:
Call to undefined function error_message() .....
mylogin auth controller:
public function auth() {
$data['title'] = 'Heart Surgeon';
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_login');
if ($this->form_validation->run() == TRUE) {
$Value['admin_username'] = $this->input->post('username');
$Value['admin_password'] =md5($this->input->post('password'));
if ($Value != null) {
$result = $this->user_model->login($Value);
if($this->session->set_userdata($result) != null){
redirect('dashboard');
}
}
} else {
$this->index();
}
}
my model
public function login($value) {
$query = $this->db->get_where('tbl_admin', $value, 1);
if ($query->num_rows() > 0) {
$row = $query->row_array();
$sess_arr = array(
'admin_user' => $row['admin_username'],
'adm_key' => $row['admin_key'],
'admin_type' => $row['admin_type'],
'admin_id' => $row['admin_id'],
'admin_logged_in' => TRUE
);
$this->session->set_userdata($sess_arr);
}
else{
$this->session->set_userdata(array('msg_type'=>'error'));
$this->session->set_flashdata('error', 'Invalid username/password');
redirect('home');
}
}
my view
<?php if (!defined('BASEPATH')) exit('No direct script access
allowed'); ?> <?php $this->load->view('layout/header'); ?>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center logo-margin ">
<img src="<?php echo base_url(); ?>assets/img/logo.png" alt=""/>
</div>
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please Sign In</h3>
</div>
<div class="panel-body">
<?php if (validation_errors()) {
?>
<div class="warning" style="padding: 0px;">
<?php echo validation_errors(); ?>
</div>
<?php
}
$atts = array(
'width' => '650',
'height' => '400',
'scrollbars' => 'yes',
'status' => 'yes',
'resizable' => 'yes',
'screenx' => '0',
'screeny' => '0'
);
?>
<div><?php echo error_message();?></div>
<?php echo form_open('home/auth'); ?>
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="username" type="email" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me">Remember Me
</label>
</div>
<!-- Change this to a button or input when using this as a form -->
<input type="submit" value="login" class="btn btn-lg btn-success btn-block">
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div> </div> <?php $this->load->view('layout/footer'); ?>
you calling wrong function to get flash error
try set flash error on controller :-
$this->session->set_flashdata('error', 'Invalid username/password');
get error flashdata on view :-
<?php echo $this->session->flashdata('error');?>
For more :- http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Basically when we set any name value pair using set_flashdata method(),
$this->session->set_flashdata('error', 'Invalid username/password');
it will automatically be discarded/removed from the session once it will be read using
$this->session->flashdata(); method.
I am 100% agreed with Rakesh.
How do i check if the user already exist in the database. I can create user but not very sure how to check if the user already exist in the databas. here are my code:
view file
<?php echo $this->navigasi->top(); ?>
<div class="container">
<br>
<h4 style="margin:0 auto;width:650px;">CREATE USER ACCOUNT</h4>
<br>
<form class="form-horizontal the-form" method="post" action="<?php echo base_url(); ?>admin/register_account">
<?php echo $this->session->flashdata('mesej'); ?>
<div class="control-group">
<label class="control-label">Name Staff:</label>
<div class="controls">
<input type="text" required name="nama_staf" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Password:</label>
<div class="controls">
<input type="password" required name="kata_laluan" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label"> Email:</label>
<div class="controls">
<input type="email" name="email" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Position:</label>
<div class="controls">
<select name="jawatan" class="span3" id="jawatan">
<option value="1">Clerk</option>
<option value="2">Technician</option>
<option value="3">Assitant officer</option>
<option value="4">Officer</option>
<option value="5">Director</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">No. Staff:</label>
<div class="controls">
<input type="text" required name="no_staf" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label"></label>
<div class="controls">
<button type="submit" class="btn btn-primary"><i class="icon-user icon-white"></i> Register</button>
controller file
class Admin extends MY_Controller {
public function index()
{
$session_data = $this->session->userdata('account');
$data['sesi_jenis'] = $session_data['jenis'];
if($data['sesi_jenis'] < 1)
{
redirect('utama');
} else {
$this->load->view('view-utama-pentadbir');
}
}
public function register()
{
$this->load->view('view-create-account');
}
public function register_account()
{
$query = $this->modeluser->createAccount();
$this->session->set_flashdata('mesej', '<span class="label label-info">Account created!</span> ');
redirect(base_url().'admin/register');
model file
class ModelUser extends CI_Model {
public function creatAccount()
{
$nameStaf = $_POST['nama_staf'];
$noStaf = $_POST['no_staf'];
$email = $_POST['email'];
$password = sha1($_POST['password']);
$jenis = 0; // user is 0 - admin is 1
$position = $_POST['position'];
$this->db->query("INSERT INTO akaun (nama_staf,no_staf,email,password,jenis,position) VALUES ('$namaStaf','$noStaf','$email','$password','$jenis','$position')");
}
public function padamAkaun($no_staf)
{
$this->db->query("DELETE FROM akaun WHERE no_staf = '$no_staf'");
}
In your controller function set validation rule as:
$this->form_validation->set_rules('email', 'Email', trim|required|valid_email|is_unique[tabelname.columnname]|xss_clean');
change model as per.considering email is unique for each user
class ModelUser extends CI_Model {
public function creatAccount()
{
$nameStaf = $_POST['nama_staf'];
$noStaf = $_POST['no_staf'];
$email = $_POST['email'];
$password = sha1($_POST['password']);
$jenis = 0; // user is 0 - admin is 1
$position = $_POST['position'];
if ($this->checkEmailExist($email) == false)
return 'ERROR! DUPLICATE USER';// or handle as you like
$this->db->query("INSERT INTO akaun (nama_staf,no_staf,email,password,jenis,position)
VALUES ('$namaStaf','$noStaf','$email','$password','$jenis','$position')");
}
public function padamAkaun($no_staf)
{
$this->db->query("DELETE FROM akaun WHERE no_staf = '$no_staf'");
}
private function checkEmailExist($email)
{
$this->db->where('email', $email);
$query = $this->db->get('akaun');
if( $query->num_rows() == 0 ){ return TRUE; } else { return FALSE; }
}
$this->form_validation->set_rules('email', 'Email','trim|required|valid_email|is_unique[tabelname.columnname]|xss_clean');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
if($this->form_validation->run() == TRUE)
{
// action after validation success.
}else{
//action after validation failure.
}