CodeIgniter: checking if user logged in for multiple pages

后端 未结 4 441
我在风中等你
我在风中等你 2020-12-12 22:52

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 redirect

4条回答
  •  甜味超标
    2020-12-12 23:19

    I use this function:

    Then just call $this->isAuthorized from your controllers __construct.

    It allows me to control what controllers are accessed and what methods are accessed too.

    protected function isAuthorized()
    {
    
        switch ( strtolower( $this->router->class ) )
        {
            case 'pages':
                $disallowLoggedOut = array( 'dashboard' );
                $disallowLoggedIn = array( 'index' );
            break;
    
            case 'users':
                $disallowLoggedOut = array( 'logout' );
                $disallowLoggedIn = array( 'register', 'login' );
            break;
        }
    
        if ( $this->session->userdata( 'loggedIn' ) ) 
        {       
            if ( in_array( $this->router->method, $disallowLoggedIn ) )
            {
                redirect( 'pages/dashboard' );
            }
        }
        else
        {       
            if ( in_array( $this->router->method, $disallowLoggedOut ) )
            {
                redirect( 'pages/index' );
            }
        }
    }
    

提交回复
热议问题