CodeIgniter global function

后端 未结 3 1415
耶瑟儿~
耶瑟儿~ 2021-01-05 02:25

Where can I place my \"global\" function, which will check, if user is logged in?

Because I want to do something like: user is able to browse some pages only when th

相关标签:
3条回答
  • 2021-01-05 03:06

    You should probably put it into a Library, and autoload the library. When you need to use the "logged_in" flag in a view, pass it in from the controller. Example:


    application/libraries/Auth.php

    <?php defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Auth
    {
    
        public function is_logged_in ()
        {
            // Change this to your actual "am I logged in?" logic
            return $_SESSION['logged_in'];
        }
    
    }
    

    application/config/autoload.php

    ...
    $autoload['libraries'] = array(
        ...
        'auth',
        ...
    }
    

    `application/controllers/welcome.php

    <?php ...
    
    public function index ()
    {
        $view_data = array
        (
            'logged_in' => $this->Auth->logged_in()
        );
        $this->load->view('my_view', $view_data);
    }
    

    application/views/my_view.php

    <? echo $logged_in ? 'Welcome back!' : 'Go login!' ?>
    
    0 讨论(0)
  • 2021-01-05 03:14

    you can use MY_controller with all function needed on every page of your website. and inherit all controllers from it. read this oficial wiki

    0 讨论(0)
  • 2021-01-05 03:27

    Are you using an authentication library? If not I'd suggest one. They come with functions like that.

    Tank Auth for example has: is_logged_in() , which does exactly what you want!

    http://www.konyukhov.com/soft/tank_auth/

    For more info about which library to use you should check out this answer which compares all libs: https://stackoverflow.com/a/476902/576223

    If you don't want an authentication library you can do as suggested by Joe

    0 讨论(0)
提交回复
热议问题