Advertisement
Google Ad Slot: content-top
CodeIgniter Tempdata
Tempdata in CodeIgniter is similar to Flashdata, but with one big difference:
- Flashdata only lasts for the next request.
- Tempdata allows you to store data in a session with a custom expiry time (in seconds).
This makes Tempdata very useful when you want temporary session data that lasts for multiple requests, but not permanently.
Example use cases:
- Store a verification token that expires in 10 minutes.
- Keep a temporary notification for a few page loads.
- Store short-lived user preferences.
🔹 Step 1: Load Session Library
First, make sure the session library is loaded.
In application/config/autoload.php:
$autoload['libraries'] = array('session');
Or load it in the controller:
$this->load->library('session');
🔹 Step 2: Set Tempdata
You can set tempdata with a custom expiry time (in seconds).
// Set tempdata with 5 minutes expiry (300 seconds)
$this->session->set_tempdata('message', 'This will last for 5 minutes.', 300);
🔹 Step 3: Retrieve Tempdata
To fetch tempdata:
echo $this->session->tempdata('message');
🔹 Example: Using Tempdata in a Controller and View
Controller (Welcome.php)
class Welcome extends CI_Controller {
public function index()
{
// Set tempdata with 10 seconds expiry
$this->session->set_tempdata('greeting', 'Hello! This message will expire in 10 seconds.', 10);
$this->load->view('welcome_message');
}
}
View (welcome_message.php)
<?php if ($this->session->tempdata('greeting')): ?>
<p style="color: blue;">
<?= $this->session->tempdata('greeting'); ?>
</p>
<?php endif; ?>