codeigniter: how to redirect after login to current controller (php_self in regular php)

后端 未结 3 766
天涯浪人
天涯浪人 2021-01-30 19:09

Well it\'s not really a problem but I check if the user exist and log them in and redirect to site/members_area, but I don\'t want to send the user to a specific page but i want

3条回答
  •  醉梦人生
    2021-01-30 19:30

    I solved this problem myself by having a login form in the header that always submits to one login controller, but the catch is that the header login form (which appears on every page) always has a hidden input called redirect which the actual login controller captures...

    Here's the basic set up (make sure the url helper is loaded):

    The Header Login Form

    The Login Controller Form

    The best part is you keep setting the redirect on failure and the redirect input only gets set if you're logging in from somewhere else.

    The Controller

    function index()
    {
        if( ! $this->form_validation->run())
        {
            // do your error handling thing
        }
        else
        {
            // log the user in, then redirect accordingly
            $this->_redirect();
        }   
    }
    
    function _redirect()
    {
        // Is there a redirect to handle?
        if( ! isset($_POST['redirect']))
        {
            redirect("site/members_area", "location");
            return;
        }
    
        // Basic check to make sure we aren't redirecting to the login page
        // current_url would be your login controller
        if($_POST['redirect'] === current_url())
        {
            redirect("site/members_area", "location");
            return;
        }
    
        redirect($_POST['redirect'], "location");
    }
    

    What's happening here is this:

    1. User logins on a different page.
    2. The login form submits to a single login controller with a hidden input element stating where they are logging in from.
    3. The login controller processes the login, then redirects based on the input.
    4. On failed login the redirect keeps getting set again, so no matter what, the user will return to the original page.

    That's just a basic example. You can obviously tweak it as needed.

提交回复
热议问题