CodeIgniter: Dynamic post-login redirection?

2019-03-11 11:05发布

问题:

I'm building a basic CodeIgniter site that requires a login before you can access any of the site.

If a user visits some site url, something like this:

http://www.mysite.com/project/detail/2049

AND they are current logged out, I have it set to automatically kick them back to the login page.

My question is, after they login, what is the best way to redirect them to the original URL they typed in, instead of say, redirecting them to the websites homepage?

I was thinking maybe, dynamically create the URL as a hidden form element in the login form and redirect there upon a successful login... What do you guys think? Is there a better/best practice for this type of dynamic post-login redirection?

回答1:

When they hit the restricted page record the uri and set it as session data with

this->session->set_userdata('redirect', 'page/uri/here');

then redirect them to the login / register

after they login check to see if 'redirect' is present with

if($this->session->userdata('redirect'))
{
    redirect($this->session->userdata('redirect'));
}

if it doesn't then take them wherever you normally take them after a login



回答2:

when attempt to access is intercepted:

redirect('/public/login/r'.$this->uri->uri_string());

so in your case, after redirection the url might look like this:

http://www.example.com/public/login/r/project/detail/2049

if the login is successful

$uri = $this->uri->uri_string();
$redirect = substr($uri, strpos($uri, '/r/')+2);
redirect($redirect);

will redirect to the original resource.

(and no, the +2 should not be +3)



回答3:

Why dont you create a session value upon login and then verify it on each page necessary to secure?

Build it into a library, so you can call the following:

$this->mylibrary->login($user);

and

$this->mylibrary->is_logged_in($user); on top of each page and automatically redirect visitors to your main site.



回答4:

I am using flashdata to redirect.

this->session->set_flashdata('redirect_url', 'page/uri/here');

after they login check to see if 'redirect_url' is present with

if($this->session->flashdata('redirect_url'))
{
    redirect(base_url().$this->session->flashdata('redirect_url')));
}

Hope this help