php session not working when redirecting in another page : <p>session is not working in my code. i have a login form, and when a user is on db the the page redirects him in main.php but it's not working</p>

<pre><code>//index.php
&lt;?php
session_start();
include('connect.php');

if(isset($_POST['submit'])){

    $username = mysqli_real_escape_string($dbCon, $_POST['username']);
    $password = mysqli_real_escape_string($dbCon, $_POST['password']);

    $sql = "select username, password from users where username='$username'";
    $res = mysqli_query($dbCon, $sql);
    if(!$res){
        die(mysqli_errno);
    }

    while ($row = mysqli_fetch_assoc($res)){
        $usr  = $row['username'];
        $pass = $row['password'];
    }

    if($username == $usr &amp;&amp; $password == $pass){
        $_SESSION["username"] = $username;
        header("Location: main.php");
        exit();
    } else {
        $error = "Invalid username or password";
    }

}
?&gt;
</code></pre>

<p>and here is my main.php</p>

<pre><code>//main.php
&lt;?php

if(isset($_SESSION["username"])) {
    $username = $_SESSION["username"];
} else {
    header('Location: index.php');
    die();
}

?&gt;
</code></pre>

<p>thanks</p>
