I Have an authentication flow as follows: I set authentication below to allow access.
<?php
session_start();
$username = $_POST["username"];
$password = $_POST["password"];
function check($username, $password){
$_SESSION['Authenticated'] = true;
$_SESSION['Expires'] = time() + 3600;
$_SESSION['username'] = $username;
header("location: ../index");
exit;
};
};
check($username, $password);
?>
On every page requiring authentication I include:
<?php
session_start();
require '../scripts/check-auth.php';
?>
Which calls this script:
<?php
$page = $_SERVER['REQUEST_URI'];
if(isset($_SESSION['Authenticated']) && $_SESSION['Authenticated']){
if($_SESSION['Expires']< time()){
$_SESSION["status_code"] = "401";
header('Location: ../views/login.php');
exit;
}
$_SESSION['Expires'] = time() + 3600;
if($page == '/views/login.php'){
header('Location: ../index.php');
exit;
}
} else {
$_SESSION["status_code"] = "401";
if($page != '/views/login.php'){
header('Location: ../views/login.php');
exit;
}
};
?>
The flow works fine for initial authentication however if it expires and then re-login it produces the error too many redirects. anyone able to assist?
The problem is in check-auth.php
, you need to unset the variables since you are going to redirect the user to the login page anyway:
<?php
$page = $_SERVER['REQUEST_URI'];
if(isset($_SESSION['Authenticated']) && $_SESSION['Authenticated']){
if($_SESSION['Expires']< time()){
unset($_SESSION['Authenticated']);
unset($_SESSION['Expires']);
$_SESSION["status_code"] = "401";
header('Location: ../views/login.php');
exit;
}
$_SESSION['Expires'] = time() + 3600;
if($page == '/views/login.php'){
header('Location: ../index.php');
exit;
}
} else {
$_SESSION["status_code"] = "401";
if($page != '/views/login.php'){
header('Location: ../views/login.php');
exit;
}
};
?>
If you don't want to unset the variables, just remove the lines of the unset()
and replace it with this line:
$_SESSION['Authenticated'] = false;
This should address the issue.