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
//index.php
<?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 && $password == $pass){
$_SESSION["username"] = $username;
header("Location: main.php");
exit();
} else {
$error = "Invalid username or password";
}
}
?>
and here is my main.php
//main.php
<?php
if(isset($_SESSION["username"])) {
$username = $_SESSION["username"];
} else {
header('Location: index.php');
die();
}
?>
thanks