CodeIgniter:检查用户是否登录多个页面 [英] CodeIgniter: checking if user logged in for multiple pages

查看:118
本文介绍了CodeIgniter:检查用户是否登录多个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它映射到我的网站的部分和其中的所有页面(方法)应该只显示,如果用户登录,否则他们应该重定向回登录屏幕。

I have a controller, which maps to section of my site and all of the pages within it (methods) should only appear if the user is logged in. Otherwise they should be redirected back to a login screen.

为了让它工作,我刚刚这样做:

To get it working I've just done this:

function index() {

    if ($this->session->userdata('logged_in')) {
        $this->load->view('main');

    } else {
        redirect('/login');
    }
}

function archive() {

    if ($this->session->userdata('logged_in')) {

等等...在每个方法中重复该检查。对控制器中的多个或所有方法执行此检查一次的最简单的方法是什么?

and so on... repeating that check in each method. What's the simplest way of doing this check once for multiple-or-all methods in the controller?

推荐答案

您可以在Controller的每个方法中运行代码,方法是在 __ construct / code>方法:

You can run code in every method of a Controller by running it in the __construct() method:

function __construct()
{
    parent::__construct();
    if ( ! $this->session->userdata('logged_in'))
    { 
        // Allow some methods?
        $allowed = array(
            'some_method_in_this_controller',
            'other_method_in_this_controller',
        );
        if ( ! in_array($this->router->fetch_method(), $allowed)
        {
            redirect('login');
        }
    }
}

如果您想限制访问整个事情,但有更好的方法来做这个,如创建一个基本控制器:

You can remove the "allowed" bits if you want to restrict access to the whole thing, but there are better ways to do this, like creating a base controller:

// Create file application/core/MY_Controller.php
class Auth_Controller extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        if ( ! $this->session->userdata('logged_in'))
        { 
            redirect('login');
        }
    }
}

然后让受限制的控制器扩展 Auth_Controller ,而不是<$ c $

Then have your restricted controllers extend Auth_Controller instead of CI_Controller. Now your code will be run every time the controller is loaded.

有关扩展核心类的更多信息: CI_Controller 现在您的代码将在每次加载控制器时运行。 http://www.codeigniter.com/user_guide/general/core_classes.html#extending-core-class =nofollow> http://www.codeigniter.com/user_guide/general/core_classes.html#extending -core-class

More info on extending core classes: http://www.codeigniter.com/user_guide/general/core_classes.html#extending-core-class

也感兴趣: http://php.net/manual/en/language.oop5.decon.php

这篇关于CodeIgniter:检查用户是否登录多个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆