'Redirect Loop happen when the session is not set

"Session.php"

if(!isset($_SESSION['username'])) 
        {                                       
           header('Location: ./index.php'); // Redirecting To Home Page per il login
           exit;
        }
session_start();// Start new session or resume existing session
    //echo 'session_id: '.session_id();
    
    require "connessione.php";
    $connessione = connessionedb("db");
    
         
    $username=$_SESSION['username'];
    $username = $connessione->real_escape_string($username);
    
    $query = "SELECT * FROM utenti where idUtente= '$username' ";
    $risultato = mysqli_query($connessione, $query);
    
    $num_record = mysqli_num_rows ($risultato);
    if ($num_record!=1)
    {
         header('Location: ./index.php'); // Redirecting To Home Page per il login
         $con->close();
         exit; 
    }

I want it to send me back to the home when there isn't a session, but it will make a redirect loop.



Solution 1:[1]

Don't do this check when you're already on index.php.

if($_SERVER['PHP_SELF'] != '/index.php' && !isset($_SESSION['username'])) 
{                                       
   header('Location: ./index.php'); // Redirecting To Home Page per il login
   exit;
}

Solution 2:[2]

Use different session check at the index file like

if(isset($_SESSION['username'])){                                       
   
   header('Location: ./dashboard.php'); // Redirecting To Dasboard Page Already logged in
   exit;

}

Solution 3:[3]

Your $_SESSION variable is not created until session_start(); is called. Since you have session_start() after you are evaluating $_SESSION['username'], it will always come back as not set because $_SESSION itself is not set yet.

Also, as Barmar pointed out, if you are requiring session.php in your index.php file, and you havent started a session yet, then it will always cause a loop. So since you are already inside index.php, just exit out. Dont redirect.

Here is the code modification:

session_start();// Start new session or resume existing session
if(!isset($_SESSION['username'])) 
    {                                       
       exit;
    }
//echo 'session_id: '.session_id();

require "connessione.php";
$connessione = connessionedb("db");

     
$username=$_SESSION['username'];
$username = $connessione->real_escape_string($username);

$query = "SELECT * FROM utenti where idUtente= '$username' ";
$risultato = mysqli_query($connessione, $query);

$num_record = mysqli_num_rows ($risultato);
if ($num_record!=1)
{
     header('Location: ./index.php'); // Redirecting To Home Page per il login
     $con->close();
     exit; 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar
Solution 2
Solution 3