Search code examples
codeignitersessioncodeigniter-2

How do i unset specified session


I wonder how i unset a specified session.

$array = array(
                'Name' => 'Jhon',
                'Age' => '19',
                'Remark' => 'Tests'
            );
$this->session->set_userdata('registrasi',$array);

I know i can delete session with

$this->session->unset_userdata('registrasi');

How do i delete Remark ? so the last result will be like this.

 'Name' => 'Jhon',
 'Age' => '19'

Solution

  • You can use unset_userdata()

    $this->session->unset_userdata()
    

    In You case

    $this->session->unset_userdata('Remark');
    

    I tired this with an my own example. Check below

    This is my session

    $session = array(
        'id' => $result[0]['id'],
        'username'  => $name,
        'logged_in' => TRUE
    );
    $this->session->set_userdata($session);
    

    Printing session

    print_r($this->session->all_userdata());
    

    Output

    Array ( 
        [session_id] => 4cc6794ab4d1ee062e377945c92148dc 
        [ip_address] => ::1 
        [user_agent] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 
        [last_activity] => 1464104585 
        [user_data] => 
            [id] => 1 
            [username] => Admin 
            [logged_in] => 1 
            [flash:new:success] => Welcome Admin 
    ) 
    

    And im going to remove username from the above session

    $this->session->unset_userdata('username');
    

    And printing back

    print_r($this->session->all_userdata());
    

    Output

    Array ( 
        [session_id] => 4cc6794ab4d1ee062e377945c92148dc 
        [ip_address] => ::1 
        [user_agent] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 
        [last_activity] => 1464104585 
        [user_data] => 
            [id] => 1 
            [logged_in] => 1 
            [flash:new:success] => Welcome Admin 
        )
    

    So this tested and works well