简体   繁体   中英

user authentication using sessions causes redirect loop

I am trying to make a authentication script, to redirect logged/unlogged users to proper page but its causing redirect loop. I have two page index.php which has the login form and the mobile.php which has the contents for valid users. For authentication i have this code on the very first lines of index.php

session_start();
if (isset($_SESSION["username"]) && isset($_SESSION["userid"])) {
    header("location: mobile.php");
    exit();
}

and the very first lines of mobile.php is

session_start();
if(!isset($_SESSION["username"])){ 
    header("location: index.php"); 
}

But I dont know why its causing a redirect loop. Here are some screenshots. Thanks for your time. 在这里您可以看到重定向这是正在发送的标题

Here are some codes from index.php, these codes lines are followed by the form for login. In the validate function all I do is check if the username and password is valid, if yes then i regenerate session id, and set session variable username and userid. and return true.

if(isset($username) && isset($password)){
    $username = preg_replace('/[^a-zA-Z0-9]/', '', $username);  
    $password = preg_replace('/[^a-zA-Z0-9]/', '', $password);
    $returnmsg = validate($username,$password);
    if($returnmsg===true){
        // header("location: mobile.php");
        exit;
    } else {
        $returnmsg = 'Invalid username or password.';
    }           
}

Allways exit after location header.

session_start();
if(!isset($_SESSION["username"])){ 
   header("location: index.php"); 
   exit();
}

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