0

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>&nbsp;&nbsp;<input type = 'text' name='startdate' maxlength = 10 size = 10 value = '2021-02-12'>&nbsp<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>&nbsp;&nbsp;<input type = 'text' name='enddate' maxlength = 10 size = 10 value = '2021-02-12'>&nbsp<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

rskakembo
  • 3
  • 4
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Mar 01 '21 at 12:38

1 Answers1

0

header.php should be included in every page that u need to protect.

<?php
session_start();
include('connection.php');

if(!isset($_SESSION) || empty($_SESSION['user'])) {
    header("Location: index.php");
    die();
}

?>

admin variable $username is missing in login, use $_POST['user'] or better $user['username'].

<?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) {
        //fetch user from database.
        $user = $result->fetch_assoc();
        $_SESSION['user'] = $user['username'];
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['userType'] = $user['level'];
        //check if user is an admin.
        if ($user['level'] === "admin") {
            echo "<script>window.location.href='http://www.pkmcapitalvendingkits.com/welcome.php'</script>";
        }
        //check if user is a normal user.
        if ($user['level'] === "op") {
            header("Location: welcome1.php");
        }

    } else {
        echo '<div class="alert">Username/password is incorrect. Click <a href="index.php">here</a> to log-in.</div>';
    }
    $stmt->close();
    //free memory used by the prepared statement.
} else {
    //username and password not provided.
};
?>

u also need protection for admin or op users. if welcome.php is only for admins u need to check

<?php
session_start();
include('connection.php');

if(!isset($_SESSION) || empty($_SESSION['user'])) {
    header("Location: index.php");
    die();
}
if($_SESSION['userType'] != 'admin')) {
    header("Location: welcome1.php");
    die();
}
?>

and welcome1.php should be accessed with op and admin i guess than original header.php its fine

Delete
  • 902
  • 7
  • 8
  • thanks for the quick response, made all the changes, included the header.php file in both welcome and authentication pages, unfortunately still behaving the way it was, even authenticated users are redirected to login, could there be something else I'm missing? – rskakembo Mar 01 '21 at 11:35
  • did u change authentication3.php? do var_dump($_SESSION) see what u get – Delete Mar 01 '21 at 11:36
  • dont put header.php to authentication3.php u still have not set the $_SESSION – Delete Mar 01 '21 at 11:41
  • yes, I copied yours exactly, I have added var_dump($_SESSION); at the end of the authentication3 file, is that not the way to do it? no output, just redirecting to login – rskakembo Mar 01 '21 at 11:52
  • let me check the last two changes first – rskakembo Mar 01 '21 at 11:53
  • do var_dump($_SESSION) on welcome.php and comment out redirect //header("Location: index.php"); to see what $_SESSION prints. – Delete Mar 01 '21 at 11:57
  • do print_r($_SESSION) if var_dump is empty – Delete Mar 01 '21 at 12:09
  • I believe its working, access can't be got through pasting a link but authenticated users get access, thank you for that. I have also noted that if an authenticated user is logged in, at that moment access can still be got through a link, is there something i can do about that? – rskakembo Mar 01 '21 at 12:09
  • I don't know exactly what u mean but that's how it should work if user is logged in he can go directly to welcome.php and every page that he has access to. That should not be a concern. – Delete Mar 01 '21 at 12:12
  • yes that works fine, what I meant was if an authenticated user logs in and their session is active, if you paste the link to the welcome page in another tab or device, it will work and they will have access to the welcome page, however, if no authenticated user is logged in, the link will not work on another tab, meaning the system works perfectly if no authenticated user is logged in currently, but if there is a logged in user, another person can use the link to access restricted pages. I hope my explanation is detailed enough – rskakembo Mar 01 '21 at 12:23
  • Well if multiple people use the same pc that user logged in that will be a problem and u cant protect against that easily. But if u log in and send me link i will not be able to see it until i login. – Delete Mar 01 '21 at 12:28
  • I understand. Again, thank you very much, for over a week I have been trying and failing. – rskakembo Mar 01 '21 at 12:37