Login in codeigniter


Login in codeigniter

我正在尝试使用以下代码登录。这个代码有问题吗?请提供正确的登录代码。。

控制器:

public function login() {
    $data = $this->data;
    $email = $this->input->post('email');
    $password = md5($this->input->post('password'));
    $result = $this->user_model->login($email, $password);
    if (count($result) !== 0) {
        $this->session->set_userdata('user_id', $email);
        $seid = $this->session->userdata('user_id');
        if ($seid == '') {
            redirect(site_url());
        } else {
            redirect('home/view');
        }
    } else {
        redirect('home/index');
    }
}

型号:

function login($email, $password) {
    $this->db->where("email", $email);
    $this->db->where("password", $password);
    $query = $this->db->get("user");
    return $query->result_array();
}

试试这个。。。

Html:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>Simple Login with CodeIgniter</title>
 </head>
 <body>
   <h1>Simple Login with CodeIgniter</h1>
   <?php echo validation_errors(); ?>
   <?php echo form_open('verifylogin'); ?>
     <label for="username">Username:</label>
     <input type="text" size="20" id="username" name="username"/>
     <br/>
     <label for="password">Password:</label>
     <input type="password" size="20" id="passowrd" name="password"/>
     <br/>
     <input type="submit" value="Login"/>
   </form>
 </body>
</html>

控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
 }
 function index()
 {
   //This method will have the credentials validation
   $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)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
     //Go to private area
     redirect('home', 'refresh');
   }
 }
 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');
   //query the database
   $result = $this->user->login($username, $password);
   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>

型号:

<?php
Class User extends CI_Model
{
 function login($username, $password)
 {
   $this -> db -> select('id, username, password');
   $this -> db -> from('users');
   $this -> db -> where('username', $username);
   $this -> db -> where('password', MD5($password));
   $this -> db -> limit(1);
   $query = $this -> db -> get();
   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }
}
?>

http://www.iluv2code.com/login-with-codeigniter-php.html

public function login(){
   $email=$this->input->post('email');
   //query the database
   $result = $this->mod_user->login($email, $password);
   if($result){
     $sess_array = array();
     foreach($result as $row){
       $sess_array = array(
         'user_id' => $row->user_id,
         'email' => $row->email
       );
       $this->session->set_userdata('sess', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('login', 'Invalid username or password');
     return false;
   }
}

function login($userName, $pass){
 $this -> db -> select('user_id, email, password');
 $this -> db -> from('tbl_users');
 $this -> db -> where('email', $email);
 $this -> db -> where('password', MD5($password));
 $this -> db -> limit(1);
 $query = $this -> db -> get();
 if($query -> num_rows() == 1)
 {
   return $query->result();
 }
 else
 {
   return false;
 }
}

试试这个。。希望它能帮助你

进行如下更改:

public function login() {
    $this->load->helper('form');
    $this->load->library('form_validation');
    $this->form_validation->set_rules('email', 'Email', 'required');
    $this->form_validation->set_rules('password', 'Password', 'required');
    // This condition check whether the request is post with valid data or not if it's not a post request than form validation return FALSE
    if ($this->form_validation->run() == FALSE) {
        // This condition check if session id is set or not if session id is set it will redirect you to homepage.
        if (isset($this->session->userdata['user_id'])) {
            redirect('home/view');
        } else {
            //else it will redirect you to login page.
            $this->load->view('login_view');
        }
    } else {
        //if it's a post request with valid data it will validate data in database.
        $email = $this->input->post('email');
        $password = md5($this->input->post('password'));
        $result = $this->user_model->login($email, $password);
        //This condition redirect you to homepage if you entered valid credentials 
        if (count($result) !== 0) {
            $this->session->set_userdata('user_id', $email);
            redirect('home/view');
        } else {
            //This will redirect you to login page with error.
            $this->session->set_flashdata('message', 'Login Fail!!<br>Invalid username or password!!');
            redirect('login');
        }
    }
}

此代码将重定向您到登录页面,以防它无法获得会话id,否则它将重定向您至主页。

型号

function fetchrowlogin($info,$table){
    $this->db->select('*');
    $this->db->where($info);
    $this->db->from($table);
    $query = $this->db->get();
    if($query->num_rows() > 0){
    $row = $query->row_array();
        return $row;
    }
}  

控制器

function login(){
    if(isset($_POST['login'])){
        $log['email'] = $_POST['email'];
        $log['password'] = $_POST['password'];
        $details = $this->User_model->fetchrowlogin($log,'candidate');
        if(count($details)){
            $ids = $details['id'];
            $email = $details['email'];
            $fname = $details['fname'];
            $this->session->set_userdata(array(
                'custid' => $ids,
                'emailid'=> $email,
                'fname'=> $fname,
            ));
            redirect('http://localhost/test27/index.php/welcome/dashboard');
        }else{
            redirect(base_url().'front1');
        }
    }
    $this->load->view('front/login');
}

创建控制器登录.php

<?php
class Login extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Common_model');
    }
    public function index()
    {
        $data['title']="Welcome to login page";
        $this->load->view('login',$data);
    }
    public function login()
    {
            $this->load->library('form_validation');
            $this->load->helper('cookie');
            $this->form_validation->set_rules('username', 'username', 'required'); 
            $this->form_validation->set_rules('password', 'password', 'required');

            if ($this->form_validation== FALSE)
            {
              $this->load->view('login');
            }
            else
            {
                $username=$this->input->post('username');
                $pass=$this->Common_model->encrypt_script($this->input->post('password'));
               // print_r($pass);exit;
                $remember=$this->input->post('remember');
                $where=array("email"=>$username , "password"=>$pass);
                //print_r($where);exit;
            if( !$data['res'] = $this->Common_model->select_where('user_master',$where))
            {
                $this->session->set_flashdata('error_message','Invalide username and password');
                // $this->session->keep_flashdata('error_message');
                $error_message=$this->session->flashdata('error_message');
                redirect(base_url().'login','refresh');
                    //echo "error";
            }
            else
            {
                $session_data=array(
                                'username'=>$username
                                );
                $this->session->set_userdata($session_data);
            if($remember != NULL)
            {
                setcookie('username',$username,time()+3600);
            }
                redirect(base_url().'control/display');
            }
        } 
    }
    public function logout()
    {
        $this->session->unset_userdata('username');
        redirect('login/login');
    }
}

创建表单登录login.php

<!DOCTYPE html>
<html lang="en">
    <!-- BEGIN HEAD -->
    <head>
    <body class=" login">
        <!-- BEGIN LOGO -->
        <div class="logo">
            <a href="<?=base_url()?>">
                <img src="<?php echo base_url('assets/pages/img/logo-big.png')?>" alt="" /> </a>
        </div>
            </a>
        </div>
        <!-- END LOGO -->
        <!-- BEGIN LOGIN -->
        <div class="content">
            <!-- BEGIN LOGIN FORM -->
             <form name="login_form" class="login-form" action="<?=base_url()?>login/login" method="post" id="login_form">
                <h3 class="form-title font-green">Sign In</h3>
                <?php
                    if (!empty(form_error('email'))) { ?>
                        <div class="text-center alert alert-danger" id="div_msg">
                            <?php echo '<label class="error-list-color">' . urldecode(form_error('email')) . '</label>';
                            ?> 
                        </div>
                    <?php } ?> 
                <?php     
                    if (!empty($msg)) {
                    ?>
                        <div class="col-sm-12 text-center alert alert-danger" id="div_msg">
                            <?php echo '<label class="error-list-color">' . urldecode($msg) . '</label>';
                            ?> 
                        </div>
                    <?php } ?>
                <div class="form-group">
                    <label class="control-label visible-ie8 visible-ie9">username</label>
                    <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" value="<?= !empty($_COOKIE['username']) ? htmlentities($_COOKIE['username']) :  set_value('username'); ?>" />
                    <p ><?php echo form_error('email'); ?></p> 
                </div>
                <div class="form-group">
                    <label class="control-label visible-ie8 visible-ie9">Password</label>
                    <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" value="<?= !empty($_COOKIE['password']) ? htmlentities($_COOKIE['password']) :  ''; ?>"/> 
                    <p><?php echo form_error('password'); ?></p>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn green uppercase">Login</button>
                    <label class="rememberme check">
                        <input type="checkbox" name="remember" value="1" />Remember </label>
                    <a href="javascript:;" id="forget-password" class="forget-password" onclick="show_forget()">Forgot Password?</a>
                </div>
                 <div class="create-account">
                <p>
                    <a href="<?=base_url()?>user_authentication">Login With Facebook</a>
                </p> 
            </div>
            </form>

            <!-- END LOGIN FORM -->
           <!-- BEGIN FORGOT PASSWORD FORM -->
            <form class="forget-form" id="forget_form" action="<?=base_url()?>admin/login/forget_password" method="post" >
                <h3 class="font-green">Forget Password ?</h3>
                <p> Enter your e-mail address below to reset your password. </p>
                <div class="form-group">
                    <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="forgot_email" />
                    <p><?php echo form_error('forgot_email'); ?></p>
                </div> 
                <div class="form-actions">
                    <button type="button" id="back-btn" onclick="show_login()" class="btn btn-default">Back</button>
                    <button type="submit" class="btn btn-success uppercase pull-right">Submit</button>
                </div>
            </form>
            <!-- END FORGOT PASSWORD FORM -->
        </div>
        <div class="copyright"> 2017 © Facil E-commerce. </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
          <script>
            $(document).ready(function() 
            {
                $("#div_msg").fadeOut(4000);
                $('#login_form').validate({
                    rules:{
                        username: {
                            required: true,
                            email: true,
                        },
                        password: {
                            required: true,
                            minlength:5
                        },
                    },
                    messages : {
                        username: {
                            required:"Please enter email address."
                        },
                        password : {
                            required:"Please enter password."
                        }
                    },
                    invalidHandler: function(event, validator) { //display error alert on form submit   
                    },
                    highlight: function(element) { // hightlight error inputs
                        $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
                    },
                    success: function(label) {
                        label.closest('.form-group').removeClass('has-error');
                        label.remove();
                    },
                });
                $('#forget_form').validate({
                    rules:{
                        forgot_email: {
                            required: true,
                            email: true
                        },        
                    },
                    messages : {
                        forgot_email: {
                            required:"Please enter email address."
                        },
                    },
                    invalidHandler: function(event, validator) { //display error alert on form submit   
                    },
                    highlight: function(element) { // hightlight error inputs
                        $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
                    },
                    success: function(label) {
                        label.closest('.form-group').removeClass('has-error');
                        label.remove();
                    },
                });
            });
            function show_forget() {
                $('#login-form').hide();
                $('#forget-form').show();
            }
            function show_login() {
               $('#forget-form').hide();
               $('#login-form').show();
            }
        </script>

    </body>
</html>