jens_vdp
jens_vdp

Reputation: 594

Codeigniter - set/check session in every controller function

i would need to use the domain and put it in a session, to retrieve some data out of the database. I can do this in my default controller, no problem with that. The problem is when people link directly to a specific controller like: www.mywebsite/mycontroller/myfunction.

When they enter the website via this link, i don't set the session from the domain and i'll get some errors.

So my question is: Does someone have a solution to check/set this session in every function of every domain?

Thanks in advance!

Upvotes: 2

Views: 1876

Answers (1)

Kalzem
Kalzem

Reputation: 7502

You can use a hook : http://ellislab.com/codeigniter/user-guide/general/hooks.html

Or you can code your small script into the construct of your controllers.

function __construct()
{
    parent::__construct();
    //Put your code here, you can also load your models and stuff
    //$this->load->model("user_model","user");
    //Code code code
}

And here is an example of a hook for i18n (language module) -- Create a file under applications/hooks/my_hook.php

function setUserLang()
{
//Getting the language of the user
//If nothing was found, stick with English
$ci =& get_instance();
if(!$ci->session->userdata('lang')){
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    switch ($lang){
        case "fr":
            $ci->session->set_userdata('lang','french');
            break;

        case "en":
            $ci->session->set_userdata('lang','english');
            break;

        default:
            $ci->session->set_userdata('lang','english');
            break;
    }
}
}

And go to applications/config/hooks.php and add something like :

$hook['post_controller_constructor'][] = array(
            'class'     => '',
            'function'  => 'setUserLang',
            'filename'  => 'my_hook.php',
            'filepath'  => 'hooks'
            );

Upvotes: 4

Related Questions