如何使用codeigniter创建用户身份验证登录页面自定义会话库

时间:2016-05-12 08:50:05

标签: codeigniter

我是一个新的codeigniter开发者,如何使用身份验证登录页面创建自定义my_session库,请帮帮我?

1 个答案:

答案 0 :(得分:-1)

首先,您需要在application / config / autoload.php中加载会话库

然后您将创建一个登录表单

<form action="<?= base_url('general/login_form')?>" method="post">
    <input type="text" name="username"><br>
    <input type="password" name="psw"><br>
    <input type="submit" value="login">
</form>

controller general.php

class General extends CI_Controller{
    public function __construct(){
        parent::__construct();

        $this->load->library(array('my_login', 'form_validation'));
    }

    public function login_form(){
        $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('psw', 'Password', 'trim|required|xss_clean');

        if ($this->form_validation->run() !== TRUE){
            $this->load->view('myform_login');
        }
        else{
            $usr   = $this->input->post('username', TRUE);
            $psw   = $this->input->post('psw', TRUE);

            $this->my_login->login($usr, $psw);
        }
    }
}

library my_login.php

class My_login{
    protected $CI;

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

        $this->CI =& get_instance();

        $this->CI->load->library('session');
    }

    public function login( $usr, $psw ){
        $result = $this->CI->db->get_where('user', array('username' => $usr, 'password' => $psw))->row();

        if( ! empty($result)){
            $this->CI->session->set_userdata(array('id'=>$result->id,'username'=>$result->username,'email'=>$result->email));

            redirect('user', 'refresh');
        }
        else{
            $this->CI->session->set_flashdata('error_login', 'Some error');

            redirect('view_index', 'refresh');
        }
    }
}

Yoou c

相关问题