Search code examples
phpjsoncodeignitersession

Passing a variable data in all controllers in codeigniter


Iam developing a website using codeigniter.I want to pass a particular data to all the controller.I searched and find it can be done by session like below.

$var = $this->session->userdata('passingdata');

But this data loses when history is cleared and when session expires.

Is there any other way to pass variable to all controllers.


Solution

  • You can try this - create MY_Controller in application/core. it looks like

    Class MY_Controller extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('HomeModel');
        $this->global_data['settings']= $this->HomeModel->getSettings();
    }
    
    function display_view($view, $local_data = array()) {
        $data = array_merge($this->global_data, $local_data);
        return $this->load->view($view, $data);
    }}
    

    then extend this controller in your all controller

    your functions in your controller like

     Class Home extends MY_Controller {
     public function index() {
        $data['title'] = 'test';       
        $this->display_view('home', $data);
    
    }
    

    }