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; ?>



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.