I tried searching other similar issues but couldn't find the solution for me, so apologies if the question is duplicated, I am also just 2 months old at this so any learning opportunity from my seniors is a blessing . Working on a web application that is supposed to keep records of operators in the field and their equipment, the frame work is up but I am facing some issues: 1. The login has 2 authentication levels, 'admin' and 'op', I got this to work better than I had hoped for, until I realized if someone copied the links to pages only accessible after login, they had access. I checked here and other places and found out it had to do with sessions, I wasn't using them because I mistakenly thought I had set the php.ini auto sessions on, but that was before I switched from the free server I was using where I controlled the files to a paid shared server, so I included sessions now and wrote a script(header.php), to check whether user has a session registered or else redirect them to the login page. The issue is when I include the script at the top of the pages I want to protect, even authenticated users are redirected back to the login page, if I don't include the script, authentication is fine but the restricted pages are not protected from using direct links. Below is the code;
authentication code(authentication3.php)
<?php
session_start();
// $con = new mysqli("host", "username", "password", "databaseName"); 
include('connection.php');
if (isset($_POST['user']) && isset($_POST['pass'])) {
    //Checking user existing in the database or not
    $query = "SELECT * FROM users WHERE username = ? and password = ?";
    //use prepared statement
    $stmt = $con->prepare($query);
    $stmt->bind_param('ss', $_POST['user'], $_POST['pass']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows !== 0) {
          $_SESSION['user'] = $username;
        //fetch user from database.
        $user = $result->fetch_assoc();
        //check if user is an admin.
        if($user['level'] === "admin") {
            $_SESSION['user'] = $username;
            $_SESSION['loggedin'] = TRUE;
             {
   
      echo"<script>window.location.href='http://www.pkmcapitalvendingkits.com/welcome.php'</script>";}
        //admin's page
        }
         //check if user is a normal user.
        if($user['level'] === "op") {
            $_SESSION['user'] = $username;
            {  
              header("Location: welcome1.php");}
              //user's page
        }
    } else {
        echo '<div class="alert">Username/password is incorrect. Click <a href="index.php">here</a> to log-in.</div>';
    }
    //free memory used by the prepared statement.
    
} else { 
    //username and password not provided.
};
?>database connection(),connection.php
<?php      
$host = "localhost";  
$user = "ronaldschwartzenneger";  
$password = "xxxxxxxxxxxx";  
$db_name = "my_db";  
  
$con = mysqli_connect($host, $user, $password, $db_name);  
if(mysqli_connect_errno()) {  
    die("Failed to connect with MySQL: ". mysqli_connect_error());  
}
?>
login page code(index.php)
  <?php
session_start();
?>
<!-- begin snippet: js hide: false console: true babel: false -->    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://w3.org/TR/html4/loose.dtd">
     <html>
       
     <head>
        <title>Operations Centre</title>
        <link rel="stylesheet" type="text/css" href="style5.css" />
        </head>
    <body>
       
            <div id="header">
            <h1>Operations Centre</h1>
        </div>
        
        <div id="container">
            <div id="bar"> 
            <form name="f1" action = "authentication3.php" onsubmit = "return validation()" method = "POST">  
                <p>  
                    <label> UserName: </label>  
                    <input type = "text" id ="user" name  = "user" />  
                </p>  
                <p>  
                    <label> Password: </label>  
                    <input type = "password" id ="pass" name  = "pass" />  
                </p>  
                <p>     
                    <input type =  "submit" id = "btn" value = "Login" />  
                </p>  
            </form>  
        </div> 
        <div id="main">
        <h1>Welcome</h1>
        <br>
        <ul>
            <li>
                Welcome to Operations Centre.
            </li>
            <div id="status">
            <li>Last Message Sent To OP</li>        </div>
        </ul>           </div>
        // validation for empty field   
        <script>  
                function validation()  
                {  
                    var id=document.f1.user.value;  
                    var ps=document.f1.pass.value;  
                    if(id.length=="" && ps.length=="") {  
                        alert("User Name and Password fields are empty");  
                        return false;  
                    }  
                    else  
                    {  
                        if(id.length=="") {  
                            alert("User Name is empty");  
                            return false;  
                        }   
                        if (ps.length=="") {  
                        alert("Password field is empty");  
                        return false;  
                        }  
                    }                             
                }  
            </script>  
    </body>     
    </html>  welcome page code(welcome.php)
<!-- begin snippet: js hide: false console: true babel: false -->    <html>
    <head>
        <title>Operations Centre</title>
        <link rel="stylesheet" type="text/css" href="style5.css" />
        <script language='JavaScript' src='calendar3.js'></script>
    <script type="text/javascript">
        function showUser(str) {
      if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
      } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
          }
        };
        xmlhttp.open("GET","getbanking.php?q="+str,true);
        xmlhttp.send();
      }
    }
    </script>
    </head>
    <body>    <?php
    include('common.php');
    ?>
    <div id="main"><h1>Banking Report</h1>
    <form>
    <select name="users" onchange="showUser(this.value)">
      <option value="">Select operator:</option>
      <option value="manager">Manager</option>
      <option value="zono">Zono</option>
      <option value="op2">OP2</option>
      <option value="op3">OP3</option>
      </select><br><br>
      <b>Start Date (YYYY-MM-DD):</b>  <input type = 'text' name='startdate' maxlength = 10 size = 10 value = '2021-02-12'> <a href='javascript:calSD.popup();'><img src='img/cal.gif' width='16' height='16' border='0' alt='Click Here to Pick a Start Date'></a><br><script language='JavaScript'>var calSD = new calendar3(document.forms['loginform'].elements['startdate']);calSD.year_scroll = true;calSD.time_comp = false;</script><br><b>End Date (YYYY-MM-DD):</b>  <input type = 'text' name='enddate' maxlength = 10 size = 10 value = '2021-02-12'> <a href='javascript:calED.popup();'><img src='img/cal.gif' width='16' height='16' border='0' alt='Click Here to Pick an End Date'></a><br><script language='JavaScript'>var calED = new calendar3(document.forms['loginform'].elements['enddate']);calED.year_scroll = true;calED.time_comp = false;</script><br><br><input type='submit' name='GetDataBDBut' value='Get Data (By Date)'><input type='submit' name='GetDataBOBut' value='Get Data (By Operator)'>
    </form>
    <br>
    <div id="txtHint"><b>Select Operator and wait...</b></div></div>
    </body>
    </html>
common.php(which is included in welcome.php)
        
    <div id="header">
            <h1>PKM Operations Centre</h1>
        </div>
        
        <div id="container">
            <div id="bar">
                <table width=100%><tr><th colspan = 2>Login Details:</th></tr><tr><th>Name:</th><td>Peter Keith Mweruka</td></tr></table>      <form name = 'logoutform' action = "logout.php" method = "post">
               <input type='submit' class='MenuButton' name='submit' value="Logout">
           </form>
           
                                            <br>
                                    
                                        <form name = 'generic' action = "" method = "post">
                                            <input type='submit' class='MenuButton' name='BankingRepBut' value= "Banking Report" formaction= "bankingreport.php">
                                            <input type='submit' class='MenuButton' name='TransactionsBut' value=   "Banking Transactions" formaction= "transactions.php">
                                                <input type='submit' class='MenuButton' name='AirtimeBut' value=    "Request Airtime" formaction= "airtimerequest.php">
                                            <input type='submit' class='MenuButton' name='OperatorBut' value= "Operator Info" formaction= "op.php">
                                            <input type='submit' class='MenuButton' name='Airtime0RepBut' value=    "Airtime Report" formaction= "airtimereport0.php">
                                        
                                            
                                            
                                            
                                            <input type='submit' class='MenuButton' name='BarredOpBut' value=   "Barred Operators" formaction= "barred.php">
                                            <input type='submit' class='MenuButton' name='ReportBut' value= 'RunDown Report' formaction= "rundown.php">
                                                <input type='submit' class='MenuButton' name='AddbankerBut' value= "Privileges" formaction= "privs.php">
                                            <input type='submit' class='MenuButton' name='BarringBut' value=    "Barring Limits" formaction= "barring.php">
                                            <input type='submit' class='MenuButton' name='PerformanceBut' value=    "Op Performance Review" formaction= "perform.php">
                                                <input type='submit' class='MenuButton' name='MachinesBut' value=   'Manage Machines' formaction= "machine.php">
                                                        <input type='submit' class='MenuButton' name='BoardsBut' value= 'Manage Boards' formaction= "boards.php">
                                            <input type='submit' class='MenuButton' name='AddOpBut' value=  "Add or Remove Operator" formaction= "addop.php">
                                            <input type='submit' class='MenuButton' name='CostsBut' value=  "Adjust Song or Video Cost" formaction= "costs.php">
                                            <input type='submit' class='MenuButton' name='OverviewBut' value=   "Records Summary" formaction= "records.php">
                                            <input type='submit' class='MenuButton' name='LoansBut' value=  'Manage Loans' formaction= "loans.php">                                 
                                            <input type='submit' class='MenuButton' name='instructionsBut' value= "Instructions" formaction= "instructions.php">    
                                        </form>
                                                </div>
header.php(the script I am trying to use to check if user is logged in)
  <?php
session_start();
    include('connection.php');
    
    if(!$_SESSION['user']) {
 header("Location: index.php");
}
    {
      
        die;
    } 
?>
   the database table I'm querying localhost/my_db/users/
SELECT * FROM users
id|username|password|level|created_at
If I include header.php, even authenticated users are redirected to index.php
 
    