Lab3: Login Example (Session)

 WAMP server side (PHP)


Database

create table users(
  id int(11) primary key auto_increment,
  userid varchar(23) not null unique,
  password varchar(80) not null
); /** Creating Users Table **/


insert the data userid as 'abc' and password as 'def' for testing

PHP
Step1 :Create a  db_connect.php
( Refer to Lab2)


Step2 :Create a login.php




<?php

// check for post data
if (isset($_POST["id"])) {
    $id = $_POST['id'];
    $pw = $_POST['pw'];
 

// include db connect class
    require_once __DIR__ . '/db_connect.php';
 // connecting to db
    $db= new DB_CONNECT();
    $db->connect();


    // get a product from products table
    $sqlCommand="SELECT * FROM users WHERE userid = '".$id."' and password ='".$pw."'";
    $result =mysqli_query($db->myconn, "$sqlCommand");

    //echo $sqlCommand;

 
    if (!empty($result)) {
        // check for empty result
        if (mysqli_num_rows($result) > 0) {
 
           echo ("Login Success");
  
 
         
        } else {
            
            echo ("Login Failed");
            
        }
    } else {
        

       echo ("Login Failed");
    }

  }
  
  else
  {

 
?>

 
<h2>Login Test</h2>

<form action= "login.php" method="post">
  User ID:<br>
  <input type="text" name="id"  required>

  <br>Password:<br>
  <input type="password" name="pw"  required>
    
  
  <br>
<br>
  <input type="submit" value="Submit">
</form> 

<br>
 
 
<?php

  }

  ?>


Step 3 :Run your Wamp server and test it 


Step 4: If Login is successful, we want user to be able to see a link to 
                         addProduct.php 



Add in the codes highlighted in yellow at login.php:

  if (mysqli_num_rows($result) > 0) {
 
           echo ("Login Success");


           ?> 
                      
                     <br>  <a href= "addStaff.php">Add Staff </a> <br>
                      
           <?php
           
              } else {
            
                        echo ("Login Failed (No data)");
            
                      }



Step 5: Test it 










Step 6: However, this is not the best solution.
If the user knows the deep link URL address for addStaff.php, the user can goto addStaff.php directly without login

E.g.


Step 6: we can use Session to prevent user to go to addStaff without Login.


Step 6A:  We will modify login.php as follows:

Add one line session_start(); in  the first line of PHP code after <?php


<?php
session_start();

// check for post data
if (isset($_POST["id"])) {
    $id = $_POST['id'];
    $pw = $_POST['pw'];
 



Add one line   $_SESSION["loginKey"] = "ok"; to create a session variable name loginKey with a value "ok"


if (mysqli_num_rows($result) > 0) {
 
           echo ("Login Success");
           
           $_SESSION["loginKey"] = "ok";


Add in the codes highlighted in yellow at login.php:

This will auto forward the page back to login.php when login Failed.

else {
            
                        echo ("Login Failed");

                        ?>

                        <meta http-equiv="refresh" content="0; URL='login.php'"/> 
                    <?php
                    
                      }


Step 6B:  We will modify addStaff.php as follows:

We will get the $_SESSION["loginKey"] and store it in $login

  $login = $_SESSION["loginKey"]

if no session variable $_SESSION["loginKey"],   $login = "notOk";

<?php
 session_start();

 if (isset($_SESSION["loginKey"] ))
 $login = $_SESSION["loginKey"] ;
 else
 $login ="notOk";
?>

<html>
<body>



Add the following codes for Logout,

On Logout it will auto forward to login.php

<meta http-equiv="refresh" content  ="0; URL='login.php'"  /> 

If user has not login before,  we show a hyperlink for user to Login

if ($login <> "ok")
 
 {
   echo "<br><h1> <a href= 'login.php'> Please Login to select Class </a> </h1>";
   
 }


if(isset($_GET['logout'])) {
  // clear the session variable, display logged out message
  
  session_destroy();
  
     echo "<br><h1> Logout  </h1>";

     ?>

<meta http-equiv="refresh" content  ="0; URL='login.php'"  /> 
 <?php
    
  
}
else
 

if ($login <> "ok")
 
 {
   echo "<br><h1> <a href= 'login.php'> Please Login to select Class </a> </h1>";
   
 }
 else



// check for required fields
if (isset($_POST['name']) && isset($_POST['tel'])) {
 
    $name = $_POST['name'];
    $tel = $_POST['tel'];


Add a hyperlink Logout at the end of the code

<a href='addStaff.php?logout=1'>Log-out</a> 

<h2>Add Staff</h2>


<form action="addStaff.php" method ="post">
  Name:<br>
  <input type="text" name="name" required>
  <br>

  Telephone Number:<br>
  <input type="text" name="tel" required>
  <br>
<br>
  <input type="submit" value="Submit">
</form> 

 
<a href='addStaff.php?logout=1'>Log-out</a> 
</body>
</html>

<?php 
 }

 ?>


Step 7: Test it out


Step 8: SQL injection Test

"Hacked" Your Login with SQL injection, we know the username but do not know the password so we enter password as aaa' or '1=1


Example 

username : abc
password :  aaa' or '1 =1


The SQL comand will becomes
SELECT * FROM users WHERE userid = 'abc' and password = 'aaa' or '1 = 1'

You will find that SQL command written in such a way is easy to be hacked with SQL injection


Step 9: Modify your code for login.php as shown below:



<?php
session_start();



// check for post data
if (isset($_POST["id"])) {
    $id = $_POST['id'];
    $pw = $_POST['pw'];
 

// include db connect class
    require_once __DIR__ . '/db_connect.php';
 // connecting to db
    $db= new DB_CONNECT();
    $db->connect();

//SELECT * FROM users WHERE userid = 'abc' and password = 1 or "1 =1"
    // get a product from products table
    $sqlCommand="SELECT * FROM users WHERE userid = '".$id."'";

   
    $result =mysqli_query($db->myconn, "$sqlCommand");

    //echo $sqlCommand;

     
    $checkLogin =false;

    if (!empty($result)) {
        // check for empty result
        if (mysqli_num_rows($result) > 0) {

          foreach($result as $row)
          {

           if ($pw == $row["password"])
          
           {
 
           echo ("Login Success");
           
           $_SESSION["loginKey"] = "ok";

           $checkLogin  =true;

           ?>



               <br>  <a href= "addStaff.php">Add Staff </a> <br>
             



           

           <?php
              
                break;
            } //end if
           
          }//end for 

               if ($checkLogin==false)
               {
                echo ("Login Failed");

               }

            
              
            }else {
            
                        echo ("Login Failed");

                        ?>

                        <meta http-equiv="refresh" content="2; URL='login.php'"/> 
                    <?php

                      }
    } else {
        

       echo ("Login Failed");
    }

  }
  
  else
  {

 
?>

 
<h2>Login Test</h2>

<form action= "login.php" method="post">
  User ID:<br>
  <input type="text" name="id"  required>

  <br>Password:<br>
  <input type="text" name="pw"  required>
    
  
  <br>
<br>
  <input type="submit" value="Submit">
</form> 

<br>
 
 
<?php

  }

  ?>

 


Step 10: Test it out with SQL injection

No comments:

Post a Comment

Note: only a member of this blog may post a comment.