CodeIgniter Forums
Redirect confusion - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: General Help (https://forum.codeigniter.com/forum-24.html)
+--- Thread: Redirect confusion (/thread-71398.html)



Redirect confusion - MightBeABitLate - 08-09-2018

HI there.

I am somewhat confused as to how to move from one controller to another. It would appear that the only way to do it is to use a redirect call like this - this is inside a controller....

Code:
class Welcome extends CI_Controller {

function __construct()
{

parent::__construct();

$this->load->library('ion_auth');
}

public function index()
{

if (!$this->ion_auth->logged_in())
{
redirect('auth/login', 'refresh');
}

$this->load->view('welcome_message');
}

Is this correct? As I understand it, this switches program flow from the Welcome Controller to the login method on the Auth controller. And inside the Auth controller, I could do something like :

Code:
if (!$this->ion_auth->logged_in())
{
// redirect them to the login page
redirect('auth/login', 'refresh');
}
else
{
redirect('welcome/index', 'refresh');
}

JMB


RE: Redirect confusion - php_rocs - 08-09-2018

@MightBeABitLate,

it looks right to me. Documentation ( https://codeigniter.com/user_guide/helpers/url_helper.html?highlight=redirect#redirect )


RE: Redirect confusion - MightBeABitLate - 08-09-2018

Thanks php-rocs.

This seems the way to effectively call a method in another controller - but of course it then transfers control TO that second controller.

JMB


RE: Redirect confusion - Pertti - 08-10-2018

If it's login related, redirecting user to specific login related URL is not that bad, is it?

You can save some time and effort by doing user auth in construct method:
PHP Code:
function __construct()
{
    
parent::__construct();
    
$this->load->library('ion_auth');
    if (!
$this->ion_auth->logged_in()) {
        
redirect('auth/login''refresh');
    }
}

public function 
index()
{
    echo 
'Only registered users will see this';


You could also add a little referrer redirect, so you save current URL before redirecting to login page controller, and on successful login you redirect visitor to that saved URL, instead of default welcome page URL.