Is $this->session->userdata and $this->session->ha

2019-07-29 05:53发布

问题:

I used use following code to authenticate in CodeIgniter.

if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
}

After reading the documentation again I found the Codeigniter has another function for it.

if(!($this->session->has_userdata('user_id'))){
            redirect(base_url());
}

If both codes are same or my code has security issues?

回答1:

Both are different functions & both of them have their own usage.

The second is better option to use because it checks whether the user_data has user_id key or not & thus runs on less code (but it is a legacy function you should use isset($_SESSION[$key]) instead of it).

the first one :-

if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}

It access the value of user_id key in userdata array in session array.

And the second one :-

if(!($this->session->has_userdata('user_id'))){
        redirect(base_url());
}

It checks whether the user_id key exists or not.

NOTE:

has_userdata($key) is a legacy method kept only for backwards compatibility with older applications. It is just an alias for isset($_SESSION[$key]) - please use that instead.

It returns TRUE if the specified key exists, FALSE if not