Please help: How can I get my login scripts to function?


#1

When the user goes to my website after the user logins in on this page they’re then presented with this page . However, if I type in the full URL webbrowserinfo.96.lt/logindone/logincode/V1/homepage.php it loads regardless if the user logins in or not. From doing my own tests it has something to do with the log out button.

Therefore, I added the code below to prevent the user from typing the full file path of the protected page and bypassing the login. However, now my index page (login page) doesn’t work when the user types in the correct user login information.

All I want is for the user to be able to login with the correct login details which is “Username: liam” and “Password: 1” and then see the login protected page. Once they get on that page click the “signout” button and be sent the the index.php page.

<?php
//check if session id is set. If it is not set, user will be redirected back to login page

if(!isset($_SESSION['username'])){
     header('Location:index.php');
     die();
}
?>

My website has three scripts here they’re if you need to see them

BELOW IS THE LOGIN PAGE CODE

<?php
   //PHP method to use cache memory to store details
   session_start();
   //Makes the "config.php" file available to be executed from this page
   require_once('dbconfig/config.php');
   ?>
<!DOCTYPE html>
<html>
   <head>
      <!-- Site title, CSS external file and font awesome -->
      <title>Login Page - Created by Liam Docherty</title>
      <link rel="stylesheet" href="css/design.css">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
   </head>
   <body>
      <div id="main-wrapper">
         <center>
            <h2>Login Form - Created by Liam Docherty</h2>
         </center>
         <div class="imgcontainer">
            <img src="imgs/icon-person-512.png" alt="Avatar" class="avatar">
         </div>
         <!-- THE FORM -->
         <!-- action="index.php" -- This attribute shows where the PHP script that does the processing is located -->
         <!-- method="post" -- The attribute identifies the action that will be performed with the data of the form. I.E. POST data to the "users" database -->
         <form action="index.php" method="post">
            <div class="inner_container">
               <label><b>Username</b></label>
               <input type="text" placeholder="Enter Username" name="username" required>
               <label><b>Password</b></label>
               <input type="password" placeholder="Enter Password" name="password" required>
               <!-- The Login button -->
               <button class="login_button" name="login" type="submit">Login</button>
               <!-- The button that is linked to the "register.php" page -->
               <a href="register.php"><button type="button" class="register_btn">Register</button></a>
            </div>
         </form>
         <?php
            //Condition, checking the Login button is pressed
            if(isset($_POST['login']))
            {
            	//The data from the Form (username & password) is stored into the @$username & @$passwordVariables
            	//You use @ before a VARIABLE in PHP when you do not want to initialise the VARIABLE before using it
            	@$username=$_POST['username'];
            	@$password=$_POST['password'];

            	//Statement that will SELECT the data from the "login" table, WHERE the Usename and Password typed match the typed ones
            	//Once the database is checked, if login details match than it stores the data in the "$query" VARIABLE
            	$query = "SELECT * FROM login WHERE username='$username' and password='$password' ";
            	//echo $query;

            	//This statement performs both the connection to the database using the values in the "$con" VARIABLE and
            	//The SELECT statement stored in the "$query" VARIABLE
            	$query_run = mysqli_query($con,$query);
            	//echo mysql_num_rows($query_run);

            	//IF the "$query_run" is run successfully, then
            	if($query_run)
            	{
            		//Check if the Username and Password exist in the database, if they exist
            		if(mysqli_num_rows($query_run)>0)
            		{
            		$row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);

            		$_SESSION['username'] = $username;
            		$_SESSION['password'] = $password;

            		//Sent the user to the "homepage.php" page
            		header( "Location: homepage.php");
            		}
            		else
            		{
            			//IF NOT, Display the message below
            			echo '<script type="text/javascript">alert("No such User exists. Invalid Credentials")</script>';
            		}
            	}

            	//IF the "$query_run" is NOT successful, then
            	else
            	{
            		//Display this message
            		echo '<script type="text/javascript">alert("Database Error")</script>';
            	}
            }
            else
            {
            }
            ?>
      </div>
   </body>
</html>

PASSWORD PROTECTED PAGE CODE

This issue with the code below is that it doesn’t let me actually login. This is good though as it stops a user just typing in the full file path of the URL and bypassing the login system.

<?php
//check if session id is set. If it is not set, user will be redirected back to login page

if(!isset($_SESSION['username'])){
     header('Location:index.php');
     die();
}
?>

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="description" content="">
      <meta name="author" content="">
      <link rel="icon" href="../../../../favicon.ico">
      <!-- Site title, CSS external file and font awesome -->
      <title>Login Page - Created by Liam Docherty</title>
      <link rel="stylesheet" href="css/design.css">
      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
   </head>
   <body class="bg-white">
      <div class="container">
         <div class="py-5 text-center">
            <img class="d-block mx-auto mb-4" src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
            <h2>Checkout form</h2>
            <p class="lead">Below is an example form built entirely with Bootstrap's form controls. Each required form group has a validation state that can be triggered by attempting to submit the form without completing it.</p>
         </div>
         <div class="row">
            <div class="col-md-4 order-md-2 mb-4">
               <h4 class="d-flex justify-content-between align-items-center mb-3">
                  <span class="text-muted">Your cart</span>
                  <span class="badge badge-secondary badge-pill">3</span>
               </h4>
               <ul class="list-group mb-3">
                  <li class="list-group-item d-flex justify-content-between lh-condensed">
                     <div>
                        <h6 class="my-0">Product name</h6>
                        <small class="text-muted">Brief description</small>
                     </div>
                     <span class="text-muted">$12</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between lh-condensed">
                     <div>
                        <h6 class="my-0">Second product</h6>
                        <small class="text-muted">Brief description</small>
                     </div>
                     <span class="text-muted">$8</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between lh-condensed">
                     <div>
                        <h6 class="my-0">Third item</h6>
                        <small class="text-muted">Brief description</small>
                     </div>
                     <span class="text-muted">$5</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between bg-light">
                     <div class="text-success">
                        <h6 class="my-0">Promo code</h6>
                        <small>EXAMPLECODE</small>
                     </div>
                     <span class="text-success">-$5</span>
                  </li>
                  <li class="list-group-item d-flex justify-content-between">
                     <span>Total (USD)</span>
                     <strong>$20</strong>
                  </li>
               </ul>
               <form class="card p-2">
                  <div class="input-group">
                     <input type="text" class="form-control" placeholder="Promo code">
                     <div class="input-group-append">
                        <button type="submit" class="btn btn-secondary">Redeem</button>
                     </div>
                  </div>
               </form>
            </div>
            <div class="col-md-8 order-md-1">
               <h4 class="mb-3">Billing address</h4>
               <form class="needs-validation" novalidate>
                  <div class="row">
                     <div class="col-md-6 mb-3">
                        <label for="firstName">First name</label>
                        <input type="text" class="form-control" id="firstName" placeholder="" value="" required>
                        <div class="invalid-feedback">
                           Valid first name is required.
                        </div>
                     </div>
                     <div class="col-md-6 mb-3">
                        <label for="lastName">Last name</label>
                        <input type="text" class="form-control" id="lastName" placeholder="" value="" required>
                        <div class="invalid-feedback">
                           Valid last name is required.
                        </div>
                     </div>
                  </div>
                  <div class="mb-3">
                     <label for="username">Username</label>
                     <div class="input-group">
                        <div class="input-group-prepend">
                           <span class="input-group-text">@</span>
                        </div>
                        <input type="text" class="form-control" id="username" placeholder="Username" required>
                        <div class="invalid-feedback" style="width: 100%;">
                           Your username is required.
                        </div>
                     </div>
                  </div>
                  <div class="mb-3">
                     <label for="email">Email <span class="text-muted">(Optional)</span></label>
                     <input type="email" class="form-control" id="email" placeholder="you@example.com">
                     <div class="invalid-feedback">
                        Please enter a valid email address for shipping updates.
                     </div>
                  </div>
                  <div class="mb-3">
                     <label for="address">Address</label>
                     <input type="text" class="form-control" id="address" placeholder="34 Hoxton liam street" required>
                     <div class="invalid-feedback">
                        Please enter your shipping address.
                     </div>
                  </div>
                  <div class="row">
                     <div class="col-md-5 mb-3">
               <!-- Logout button -->
                <a class="btn btn-primary" href="index.php" role="button">Signout button</a>
               </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>

#2

Do you have a session_start() statement in the protected page code, before you try to reference the $_SESSION variable?

Next, there are a bunch of implementation problems -

  1. The form processing code need to be above the start of the html document.
  2. Do NOT use the @ error suppressor, ever. You want to have all php errors either displayed or logged so that you will know when something goes wrong.
  3. You need to validate all input data before using it. If either one or both of the inputs to your code are empty, there’s no point in wasting time running a query using them.
  4. You need to hash the stored password in order to help protect your user’s stored information. See php’s password_hash() and password_verify() functions.
  5. You need to use exceptions to handle database errors and in most cases let php catch the exception, where it will use its error related settings to control what happens with the actual error information.
  6. For SELECT queries, you can just fetch the data and test if the fetch was successful.
  7. The only value you should store in a session variable is the user’s id, from an auto-increment column in your database table. You shouldn’t store the password ever and by storing the username, it will take more code to allow the username to be edited, since you must change it in the database table where it is stored and also in the currently active session variable. To get any user information, use the user id in the session variable and query the database table to get the current values.
  8. You need an exit/die statement after all header() redirects to prevent the remainder of the code from running. A header() statement doesn’t stop program execution.

#3
  1. When supplying external/unknown data to an sql query statement, use a prepared query, with a place-holder in the sql for each data value, then supply the data when the query gets executed. The easiest way of doing this is to switch to the much simpler php PDO database extension. The mysqli extension you are using is overly complicated and inconsistent when dealing with prepared queries.

#4

And what is your logout code?