Skip to content

Check Sessions with One Function

World Wide Web Server edited this page Jul 4, 2012 · 6 revisions

I have been toying around for weeks on the best solution on how to check for session data before allowing the user to access admin sections of their website.

Today I played around with creating a helper function that will do just that.

Helper File (session_helper.php) [code] <?php //Function returns the CI instance //================================ //Usage: //================================ //ci_instance()->uri->segment(3); //================================ //Replaces: //================================ //$ci =& get_instance(); //================================ if(!function_exists('ci_instance')) { function ci_instance() { return get_instance(); } }

if(!function_exists('check_sessions')) {
    function check_sessions($session_name) {
        if(is_array($session_name)) {
            foreach($session_name as $s) {
                a($s);
            }
        } else {
            a($session_name);
        }
    }
}

if(!function_exists('a')) {
    function a($session_name) {
        if(ci_instance()->session->userdata($session_name)) {
            return true;
        } else {
            redirect('/');
        }
    }
}

/* End of file session_helper.php / / Location: /application/helpers/session_helper.php */ [/code]

Controller (admin_panel.php) [code] <?php Class Admin_panel extends Controller { function Admin_panel() { parent::Controller(); //check one session data check_sessions('username');

        //check multiple session data
        check_sessions(array('username', 'id'));
    }
    
    function index() {
        $this->load->view('admin_panel_view');
    }
}

/* End of file admin_panel.php / / Location: /application/controllers/admin_panel.php */ [/code]

Take note that I am auto loading my helper file in autoload.php

Hope this helps!

Clone this wiki locally