简体   繁体   中英

Redirect user to login form

Dears,

I create a function that permits to redirect the user to a specific URL. The function is named redirect and user the header function:

public function redirect($url, $code = null)
{
    if($code == 301){
        header("HTTP/1.1 301 Moved Permanently");
    }
    header('Location: '.Router::url($url));
    die();
}

I use it to protect some pages to be reachable for a none authenticated users. I put a condition, permits to check if user is logged, if not will be redirected to the login form:

if(!$this->Session->isLogged()){
    $this->redirect('users/login');
}

The function isLogged is:

public function isLogged()
{
    return isset($_SESSION['User'][0]->id);
}

I tried to do the same things, for BO admin pages and it works. But I need to protect the front pages too. The problem is when I try to access to a front-page, I'm redirect to the login form, but I got the ERR_TOO_MANY_REDIRECTS error on my Chrome browser.

I tried to delete cookies, but I have the same problem. When I try to ignore the following line, I can see my login form:

if(!$this->Session->isLogged()){
    $this->redirect('users/login');}

You should not attempt to redirect to login in case you are already on that page.

if(!$this->Session->isLogged() && !$this->isLoginPage()){
  $this->redirect('users/login');}
}

PHP raises this error in two main cases:

  1. Infinite redirecting: you're probably invoking your mentioned function for an infinite number of times
  2. Too many redirects in a row: the "Header" native PHP's function handle only one header per instance.

In a nutshell: the error related to your case is quite surely related to an infinite redirect, otherwise there could be other redirects invoked moreover the wanted one in the page where you're calling your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM