robins robins - 1 month ago 9
PHP Question

How to pass a data with redirect in codeigniter

In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect

$in=1;
redirect(base_url()."home/index/".$in);


and my index function is

function index($in)
{
if($in==1)
{

}
}


But I'm getting some errors like undefined variables.

How can i solve this?

Answer

So in the controller you can have in one function :

$in=1;
redirect(base_url()."home/index/".$in);

And in the target function you can access the $in value like this :

$in = $this->uri->segment(3);   
if(!is_numeric($in))
{
  redirect();       
}else{
   if($in == 1){

   }
}

I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).

Hope that helps.