为什么CodeIgniter中的flashdata并不总是有效,而userdata总能工作?

I have one code block for assigning some values to flashdata in report controller and another block for accessing flashdata in export_data controller.

Report Controller:

if ($this->input->get_post('date_frm')) {
              $conditions[] = 'appointment_date >= "'.trim($this->input->get_post('date_frm', TRUE)).'"';
            }

            if ($this->input->get_post('date_to')) {
              $conditions[] = 'appointment_date <= "'.trim($this->input->get_post('date_to', TRUE)).'"';
            }

            $conditions = $this->search_model->searchterm_handler($conditions);

            $this->session->set_flashdata('ext_data', $conditions);

And in Export_data Controller:

$myVar = $this->session->flashdata('ext_data');
    $this->session->keep_flashdata('ext_data');

It does not always work, but when I use userdata rather than flashdata it is working fine. Why?

OP: when I use userdata rather than flashdata it is working fine

Data set with flashdata() is only saved for a one-time request, then cleared out:

Documentation: CodeIgniter supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.

...and keep_flashdata() only saves the data for one additional request after the first:

Documentation: If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() method.


However, userdata() is always available until the session is destroyed.

See: What is Session Data?


I think you should read the full documentation: Session Library

First You Should Know what is flashdata.

It does not clear session value when it is called.Even it is available for next server call and will not be available for 2nd call.

As an example suppose you have two function in a controller

function test1()
{
    $this->session->set_flashdata('ext_data', 'test');
}
function test2()
{
    echo $this->session->userdata('ext_data');
    echo $this->session->userdata('ext_data');
    echo $this->session->userdata('ext_data');
}

Now if you call your_site_url/controller/test1 it will set test for ext_data

After that if you call your_site_url/controller/test2 it will print test word 3 times means you can use this session variable for this time as much you want but for next call(hit again your_site_url/controller/test2) it will be blank.

Hope you understand what does it mean.

CodeIgniter supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.