Rooneyl
Rooneyl

Reputation: 7902

Redirect in Codeigniter

I have a paginated display in which on each page call I set the current URI string into a session (in my controller).

$current = $this->uri->uri_string();
$this->session->set_userdata('return_to', $current);

From the view the user can click a link to go somewhere else (an edit form), which when submitted (and form validation is correct) I want to return to the correct page of the paginated results.

if($this->form_validation->run('edit') == TRUE )
{
    $back_to = NULL;
    $back_to = '/'.$this->session->userdata('return_to');
    ....
    redirect($back_to);
}

Seems to work sometimes in Firefox but dies in Chrome, redirect to favicon.ico

Any and all help appreciated

UPDATE: My problem isn't due to relative/absolute addresses, for some weird reason in the second controller the redirect aims to favicon.ico, not what was stored in the session.

Upvotes: 3

Views: 7636

Answers (2)

Damien Pirsy
Damien Pirsy

Reputation: 25435

if($this->form_validation->run() == TRUE )
{
    if($this->session->userdata('return_to')
    {
       redirect($this->session->userdata('return_to'));
    }
    else
    {
      redirect(base_url());
     // or trigger some error
    }
}

Don't need to assign a variable, redirect() uses both a full url and a segmented url (much like site_url(), which is exactly what is returned by uri_string().

So if this doesn't work, it's likely your session is not set or expired. Also, consider that CI's sessions are cookies , so a browser can has its role in here.

Upvotes: 1

Sean H Jenkins
Sean H Jenkins

Reputation: 1780

I would use an absolute URL and not a relative one.

Try this

if($this->form_validation->run('edit') == TRUE )
{
    $back_to = NULL;
    $back_to = 'http://www.mydomain.com/'.$this->session->userdata('return_to');
    ....
    redirect($back_to);
}

As stealthyninja pointed out it's probably better to use CodeIgniter's site_url() or base_url() instead of hard coding it. Set the site_url() in the config.php (i believe)

Upvotes: 0

Related Questions