简体   繁体   中英

Codeigniter: session class in routes.php

How can I access the codeigniter session class inside routes.php?

I need that class to route all the request (except /login) to a certain controller, unless the user has admin privileges ( $this->session->userdata('logged') ).

All the route rules are working, I only need to access that class.

You are not typically able to access the Singleton ($this->) from the config & routes file because the classes are not loaded at that point

although there are a few workarounds to access the session, the better way would be to a MY_Controller & the _remap() function:

http://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping

Here's some sample code that explains a little more about how they work:

http://www.codebyjeff.com/blog/2012/11/ci-_remap-function-the-friend-you-never-knew-you-had

Create this MY_Controller and store it in application/core/ , then have your other controllers extend it:

<?php if (! defined('BASEPATH')) exit('No direct script access');

class MY_Controller extends CI_Controller {

function __construct() {
    parent::__construct();
    $this->_check_auth();
}

private function _check_auth(){
    if(!$this->session->userdata('is_admin')){
        $this->session->sess_destroy();
        redirect('login');
    }
}
}

Note: above code assumes you already have a user login system in place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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