如何使用CodeIgniter下的钩子禁止访问页面

时间:2017-03-23 15:39:40

标签: php codeigniter

您好我在CI下禁止输入页面时遇到了一些问题。根据连接的用户的等级,他将能够看到或不是输入页面。 这是我在application / hooks / forbidden.php中的钩子:

 <?php
class forbid
{
    private $CI;
        function forbidden()
        {
               if ($this->session->userdata('logged_in')) {
            foreach ($this->session->userdata('ranked_in') as $rank)
            {
                switch ($rank)
                 {
                    case $rank== 1:     //Admin
                        redirect('home', 'refresh');
                        break;


                     case $rank== 4:    //student
                     {
                        if(($_SERVER['REQUEST_URI']) == '/project/input')
                        {
                            redirect ('student','refresh');
                        }
                     }
                        break;
                 }
            }

         }else{
        $this->load->helper(array('form'));
        $this->load->view('login');
         }

        }

}
?>

我的愿望是在排名用户为4时重定向到学生页面,但在测试时没有任何反应。我做错了什么或者误解了什么?谢谢你的帮助!

编辑: 在配置文件中启用了挂钩。 配置/挂钩中的钩点:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files.  Please see the user guide for info:
|
|   https://codeigniter.com/user_guide/general/hooks.html
|
*/

$hook['pre-controller'] = array(
        'class' => 'forbid',
        'function' => 'forbidden',
        'filename' =>  'forbidden',
        'filepath' =>   'hooks',
        'params' => array()

    );

?>

1 个答案:

答案 0 :(得分:0)

如果没有完整的代码图片,很难看到。以下是我在最近的一个项目中的表现。

此代码进入/application/config/hooks.php - 也许您可以复制并调整它以满足您的需求。

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files.  Please see the user guide for info:
|
|   https://codeigniter.com/user_guide/general/hooks.html
|
*/

// Force Login
$hook['post_controller_constructor'] = function()
{

    $CI =& get_instance();

    $publicPages = array(
        'debug',
        'login',
        'logout',
        'password-reset',
        'api',
        'api/3D-complete',
        'api/refund',
        'api/3D-enrolment-check'
    );

    $publicRegexPages = array(
        'password-reset-verification',
        'psp',
        'cron'
    );

    if(!$CI->session->userdata('isLoggedIn') && !in_array($CI->uri->uri_string, $publicPages) && !in_array($CI->uri->segment(1), $publicRegexPages))
    {

        $intendedPage = $CI->uri->uri_string;

        redirect('login?redirect=' . $intendedPage);

    }

};