How to Work Tempdata in Codeigniter

In some project, where you want to remove data stored in session after some specific unique time-period, this can be done using tempdata functionality in CodeIgniter. You may also like How to create flash messages in Codeigniter and How to Session Management in Codeigniter.

Steps For How to Work Tempdata in Codeigniter

Step 1: Add Tempdata

To add data as tempdata, we have to use mark_as_temp() function. This function takes two argument items first argument is a tempdata second one is a expiration time.

// 'value' will be erased after 300 seconds(5 minutes) 
$this->session->mark_as_temp('value',300);

You can also pass an array to store multiple data. All the items value stored below will be expired after 300 seconds.

$this->session->mark_as_temp(array('value1','value2'),300);

You can also set different expiration time for each item as shown below.

// 'value1' will be erased after 250 seconds, while 'value2' 
// will do so after only 300 seconds 

$this->session->mark_as_temp(array( 
   'value1'=>250, 
   'value2'=>300 
));

Step 2: Retrieve Tempdata

We can retrieve the tempdata using tempdata() function.

$this->session->tempdata('value');

Step 3: Remove Tempdata

Tempdata is removed automatically after its expiration time but if you want to remove tempdata before that, then you can do as shown below using the unset_tempdata() function, which takes one argument of the item to be removed.

$this->session->unset_tempdata('value');

And if you like this tutorials please share it with your friends via Email or Social Media.

Leave a Reply

Your email address will not be published. Required fields are marked *