post data via redirect function in codeigniter

2019-01-29 00:40发布

问题:

Is there ever a way or some tricks to post an array of data or a single variable string data using redirect() function in codeiginter?

回答1:

when using redirect you go from one controller or another by this process all post data are destroyed unless you stored them on a session, here is how i do it

$data = array('firstname'=>'fname','lastname'=>'lastname');
// i store data to flashdata
$this->session->set_flashdata('lolwut',$data);
// after storing i redirect it to the controller
redirect('controller/method')

so on your redirected controller you can access it via $this->session->flashdata('lolwut') note that i am using flashdata not userdata, flashdata destroys itself on the next process.

read more flashdata here SESSION CLASS



回答2:

In the first place why you need post data while redirect :

you can have post function that handle all your code and then redirect after success or failure depends on your usage

function method()
{
    //do something
    redirect('path/to/method');
}

if you want to have variables passed through other pages you can do this by :

  1. Save data into session, $this->session->set_data($data); or $this->set_flashdata($data); depends on your usage
  2. Pass in URL as parameter instead of form submission

hope that helped you someway