zoukankan      html  css  js  c++  java
  • Codeigniter-实现权限认证

    两种方法

    1. 钩子函数
    2. 集成核心Controller

    方法一,钩子函数:

    一直没找到CI的权限认证扩展,以前好像找到过一个老外的扩展,不过不怎么好用,现在记不清了,后来仿着jsp firter的方式用CI钩子写了一下,感觉还可以,做个小网站,小应用足够了,没必要搞得太复杂。看到很多人在网上问,这里把我们的方法分享一下,如果你有更好的实现,也请记得分享给我们。^_^

    通常我们后台路径看起来都会像下面这样:

    http://www.php-chongqing.com/index.php/manage/

    http://www.php-chongqing.com/index.php/manage/article/add

    http://www.php-chongqing.com/index.php/manage/product/delete/1

    http://www.php-chongqing.com/index.php/manage/user


    因为CI是MVC的,单一入口,并且给我们提供了7个挂钩点,一切就很简单了,我们只需要在CI执行目标控制器方法之前拦截到请求,检查URI是否是以manage开头即可,如果URI以manage开头,就检查用户权限,没有权限就跳转到登陆页或是相关的提示页。


    1、先到config/config.php中设置允许使用钩子

    $config['enable_hooks'] = TRUE;
    2、再到config/hooks.php中配置权限认证钩子

    $hook['post_controller_constructor'] = array(    'class'    => 'ManageAuth',    'function' => 'auth',    'filename' => 'ManageAuth.php',    'filepath' => 'hooks');
    需要注意的是一定要使用'post_controller_constructor'挂钩点,因为我们可能要在ManageAuth中使用CI的aip,连接数据库等。


    3、创建ManageAuth.php文件,放到hooks目录下,ManageAuth.php中的代码如下:

    /** * * 后台权限拦截钩子 * @link http://www.php-chongqing.com * @author bing.peng *  */class ManageAuth {    private $CI;            public function __construct() {        $this->CI = &get_instance();     }            /**     * 权限认证     */    public function auth() {        $this->CI->load->helper('url');        if ( preg_match("/manage.*/i", uri_string()) ) {        // 需要进行权限检查的URL            $this->CI->load->library('session');            if( !$this->CI->session->userdata('username') ) {        // 用户未登陆                redirect('login');                return;            }        }            }        }

    OK,就这样,搞定了,我们通过正则表达匹配,凡是以manage打头的url都是需要登陆后才能访问的。

    示例中的权限认证很简单,仅仅只是检查下session是否存有username,如果有就认为用户已登陆,可以访问资源,否则就跳转到登陆页面。注意登陆的url千万不是能以manage开头,否则就重向定死循环了。


    如果,你须更复杂的权限认证直接写你自己的认证方法就OK了,比如你使用了用户、角色、资源等等。


    这种实现基本可以算作AOP(面向切面编程)了,其实PHP已经有了AOP的雏形,改天用原生PHP的方法拦截,实现一下权限认证。^_^

    参考官方文档:http://codeigniter.org.cn/user_guide/general/hooks.html

    方法二,集成核心Controller:

    <?php
    class Extend_Controller extends CI_Controller {
    public function __construct() {
    parent::__construct();
    }
    }

    查看官方文档:http://codeigniter.org.cn/user_guide/general/core_classes.html

  • 相关阅读:
    Codeforces 834D The Bakery
    hdu 1394 Minimum Inversion Number
    Codeforces 837E Vasya's Function
    Codeforces 837D Round Subset
    Codeforces 825E Minimal Labels
    Codeforces 437D The Child and Zoo
    Codeforces 822D My pretty girl Noora
    Codeforces 799D Field expansion
    Codeforces 438D The Child and Sequence
    Codeforces Round #427 (Div. 2) Problem D Palindromic characteristics (Codeforces 835D)
  • 原文地址:https://www.cnblogs.com/KTblog/p/5861851.html
Copyright © 2011-2022 走看看