Not giving access to certain method in controller when session is not set in codeigniter
Check this It might help you
class MY_controller extends CI_controller{ function __construct() { parent::__construct(); } function _required_user($params =array()){ $action =$this->router->fetch_method(); if(empty($params['except'])) $params['except'] =array(); if(empty($params['only'])) $params['only'] =array(); if(count($params['except']) > 0 && in_array($action,$params['except'])) return true; if(count($params['only']) > 0 && in_array($action,$params['only']) && $this->session->userdata('is_login')) return true; if($this->session->userdata('is_login')) return true; redirect('login'); } }class dashboard extends MY_Controller { function __construct() { parent::__construct(); $this->load->library('session'); $this->load->model('dbmodel'); $this->load->helper('url','form'); $this->_required_user(array('except'=>array('index'))) } function add(){ /* Session required */ } function edit(){ /* Session required */ } function index(){ /* no session required */ } } class content extends MY_Controller{ function __construct() { parent::__construct(); $this->load->library('session'); $this->load->model('dbmodel'); $this->load->helper('url','form'); $this->_required_user(array('only'=>array('index'))) } function add(){ /* no Session required */ } function edit(){ /* no Session required */ } function index(){ /* session required */ } } class Myaccount extends MY_Controller{ function __construct() { parent::__construct(); /* for all functions session required */ $this->_required_user() } function edit(){ /* session required */ } function save(){ /* session required */ } }
- Only param: check session is exist for only given functions/function
- Except param: Don't check session for given functions/function
- No Param : check session for all function in controller and redirect
You can modified _reuired_user function according to your requirement
you can try the following - if it helps
create in your application/core folder a class named MY_Controllersomething like
class MY_Controller extends CI_Controller{ public function checkUserSession() { if($this->session->userdata("unverified") != FALSE) { redirect("verify_user"); } return true; }}
after that your dashboard controller should look like
class dashboard extends MY_Controller { public function show_dashboard() { if ($this->checkUserSession()) { //your code } }}
Create a library with any name i created Users.
class Users { public function __construct() { $this->ci =& get_instance(); } function _is_logged() { if(!$this->ci->session->has_userdata('unverified')) { redirect('verify_user'); } }}
Load the library or put it in to autoload in application/config/autoload.php
Then just call the function at the top of your methods which one you want to restrict.
function abc(){ $this->users->_is_logged(); // your code}