W3docs

Redirect with CodeIgniter

In CodeIgniter, you can use the redirect() function to redirect the user's browser to a new page.

In CodeIgniter, you can use the redirect() function to redirect the user's browser to a new page. This function is part of the CodeIgniter's URL Helper, so you will need to load the URL Helper before using it.

Here's an example of how to use the redirect() function:

How to use the redirect() function to redirect the user's browser to a new page in Codeigniter?

// Load the URL Helper
$this->load->helper('url');

// Redirect the user's browser to the desired URL
redirect('http://example.com/mypage');

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also use the redirect() function to redirect the user to a different controller or method within your CodeIgniter application. For example:

How to use the redirect() function to redirect the user to a different controller or method within the CodeIgniter application?

// Redirect the user to the "welcome" controller
redirect('welcome');

// Redirect the user to the "welcome" controller's "greeting" method
redirect('welcome/greeting');

The redirect() function also allows you to pass additional segments to the destination URL. For example:

How to use the redirect() function to pass additional segments to the destination URL within the CodeIgniter application?

// Redirect the user to the "welcome" controller's "greeting" method,
// passing the user's name as a URL segment
redirect('welcome/greeting/John');

You can also use the redirect() function to pass flash data, which will be available only for the next server request. This can be useful for displaying messages to the user after a form submission or other action.

How to use the redirect() function to pass flash data in Codeigniter?

// Set a message to be displayed to the user
$this->session->set_flashdata('message', 'Your form was successfully submitted!');

// Redirect the user to the "welcome" controller
redirect('welcome');

Then, in your "welcome" controller or view, you can retrieve and display the flash data message like this:

Example of retrieving and displaying a flash data message in Codeigniter

echo $this->session->flashdata('message');