简体   繁体   English

如何在CodeIgniter上实现登录的正确方法?

[英]How is the right way to implement login on CodeIgniter?

I'm practicing Codeigniter framework using a small project from my friends. 我正在使用朋友的一个小项目来练习Codeigniter框架。 Each pages need to load layout view and content view separately. 每个页面都需要分别加载布局视图和内容视图。 The layout show users login info (logged or not, name, picture, etc.). 该布局显示用户登录信息(是否登录,名称,图片等)。 The question is, how to show login info for each action efficiently? 问题是,如何有效显示每个动作的登录信息? Most of the action will load the layout view, so i need to do that right. 大多数操作将加载布局视图,因此我需要正确执行此操作。

I do implement a helper to get user model, but is that right? 我确实实现了一个帮助程序来获取用户模型,但这是对的吗?

Frist Create Login Controller, in that controller 在该控制器中第一个创建登录控制器

  • Ask User to login 要求用户登录
  • Check if password is correct. 检查密码是否正确。 If yes, set session value (say user_id) & redirect to User Controller. 如果是,请设置会话值(例如user_id)并重定向到用户控制器。

Second Create User Controller, in that controller's constructor function 第二个创建用户控制器,在该控制器的构造函数中

  • Check Session user_id exist or not. 检查会话user_id是否存在。 If no, redirect to login. 如果否,请重定向到登录。

It is best to check at constructor because it will check for all the methods in that controller. 最好检查构造函数,因为它将检查该控制器中的所有方法。

Hope it helps. 希望能帮助到你。

You can use the following method:- 您可以使用以下方法:

In one separate model constructor function check the login details 在一个单独的模型构造函数中,检查登录详细信息

class Auth extends CI_Model {

    public function __construct(){

        parent::__construct();

        $this->load->model('loginModel');

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

        if(!$this->loginModel->isLogin()){

            $this->session->sess_destroy();

            redirect('index.php/auth/login','refresh');

            exit;

        }

    }
}

Then in required controllers include the model in the controller constructor function 然后在所需的控制器中将模型包括在控制器构造函数中

class Main extends CI_Controller {

    public function __construct(){
        parent::__construct();      
        $this->load->model('auth');
    }

} 

No need to check all the controller action's if you added in the controller constructor it will check for all the actions 如果您添加了控制器构造函数,则无需检查所有控制器动作,它将检查所有动作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM