php - My session is not passing to the different page

The session is not passing and I want to restrict the users from viewing the login page while they are logged in for that I tried many things but it didn't work:

My login page

<?php 

    error_reporting(E_ALL);
    ini_set('display_errors',1);

    require_once('connect.php');
    extract($_POST);

    $result = mysqli_query($link, "SELECT * FROM users ");

    $row = mysqli_fetch_assoc($result);
    //var_dump($row['username']);
    //var_dump($row['password']);
    if(isset($_POST['login'])){
        $username = $_POST['username'];
        $password = md5($_POST['password']); 
        if ($username == $row['username'] && $password == $row['password']){
            session_start();
            $_SESSION['nID'] = true;

            //echo"Login"; 
            header('Location: home.php');
        } else {
            echo"Login failed"; 
        }
    }
?>

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div id="frm">

        <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
            <h1> Login</h1>
        <p>
        <label>Username</label>
        <input type="text" id="username" name="username" />
        </p>

        <p>
        <label>password</label>
        <input type="password" id="password" name="password"/>
        </p>
        <p>
        <input type="submit" id="btn" value="login" name="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
        </p>
        <p>
        Not yet a member <a href="register.php">Register here</a>


        </form>
        </div>
    </body>
</html>

My home page

<?php
    session_start();
    if ($_SESSION['nID'] == false) {
        header("Location: login.php");
        die();
    } elseif ($_SESSION['nID'] == true) {
        header("Location: Home.php");
        die();
    } else {
        echo"cant connect";
    }
?>
<html>
<head>
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<ul class="nav nav-pills">
  <li role="presentation" class="active"><a href="welcome.php">Home</a></li>
  <li role="presentation"><a href="info.php">Information</a></li>
  <li><a href="logout.php">Logout</a>
</ul>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</body>
</html>

The session is not passing and it doesn't prevent the user from viewing the homepage while they aren't logged in.

I have tried many different things but nothing seems to work.

6 Answers

  1. Alex- Reply

    2019-11-16

    Some thoughts on this question:

    • 1) Stop using extract(). You simply don't need it.

      Warning
      Do not use extract() on untrusted data, like user input (i.e. $_POST, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.

      From the Manual.

    • 2) As noted in another answer Your SQL query is far too vague; you're returning the first answer of a search of the whole DB rather than searching for any specific criteria.

      SELECT password FROM users WHERE username=username_here LIMIT 1
      

      And then take this row and compare with the given password:

      if($password === $row['password'])
      
    • 3) Your password system used on MySQL / PHP is NOT GOOD ENOUGH. Stop using md5() and employ password_hash and password_verify PHP functions. Please read how to do it properly and this comment.

    • 4) Every time you use header("Location: ...") to redirect the user it is highly recommended you add a die or exit command immediately afterwards in order to cease the code execution on the current page. For example:

      header("Location: this_page_will_never_load.php");
      header("Location: this_page_will_always_load_instead.php");
      
    • 5) require and include functions do not require brackets.


    NOTE

    Re the numerous answers here referencing session_start(); if session_start() is called after output is sent to the browser, then there will be an error notice generated. OP has not reported an error notice even with:

       error_reporting(E_ALL);
       ini_set('display_errors',1);
    

    So session_start() placement in the code is not an issue in this specific situation.

    However:
    It is best practise to put your session_start() as early as possible in your code and before such debug things as var_dump which would cause session_start not to load becase var_dump has already thrown data out to the browser.


    Finally, an answer to your problem:

    I want to restrict the users from viewing the login page while they are logged in for that I tried many things but it didn't work:

    Your code in login.php:

       if(isset($_POST['login'])){
            ///session stuff etc. 
        }
    

    The above code on your login.php page will only execute if the page is being given POSTed data. What you have is that once someone is logged in correctly and they then return to the login.php page, they are not resubmitting the POSTed data so this code block is simply not running.

    Because this code block contains all your $_SESSION references this is why it looks like $_SESSION is not running.

    Instead you want to do this (simplified) in login.php:

    session_start();
    if(isset($_POST['login'])){
        // setup session values, 
        // once POSTed login data is checked and authorised in the database
        $_SESSION['nID'] = true;
    }
    elseif ($_SESSION['nID'] === true){
         // is already logged in so redirect to the index page. 
         header("Location: index.php");
         exit;
    }
    else {
         // this fires if no POSTed data is sent and no valid 
         // session is found. 
    }
    
  2. Alan- Reply

    2019-11-16

    try this condition in your home.php

    session_start();
    if (!isset($_SESSION['nID']) || empty($_SESSION['nId'])) {
       header("Location: login.php");
       die();
    }
    
  3. Albert- Reply

    2019-11-16

    <?php 
    session_start();
        error_reporting(E_ALL);
        ini_set('display_errors',1);
    
        require_once('connect.php');
        extract($_POST);
    
        $result = mysqli_query($link, "SELECT * FROM users ");
    
        $row = mysqli_fetch_assoc($result);
        //var_dump($row['username']);
        //var_dump($row['password']);
        if(isset($_POST['login'])){
            $username = $_POST['username'];
            $password = md5($_POST['password']); 
            if ($username == $row['username'] && $password == $row['password']){
                //session_start(); removed it
                $_SESSION['nID'] = true;
    
                //echo"Login"; 
                header('Location: home.php');
            } else {
                echo"Login failed"; 
            }
        }
    ?>
    

    UPDATE, you try this code

    Every page you need to add session_start() in page heading

  4. Andrew- Reply

    2019-11-16

    1st : First of all, your query is wrong. You're always checking the value with first user in table . You need to query with the where clause.

    SELECT * FROM users WHERE username=username_here AND password=hash_password_here
    

    2nd : Your If statement should be like the following.

    <?php
    
         session_start();
        if (!isset($_SESSION['nID'])) {
    
           header("Location: login.php");
            die();
    
        } 
    ?>
    

    3Rd : Try to use prepared statements to avoid sql injection.

    $stmt = $link->prepare("SELECT * FROM users where username=? and password=?");
    
    $stmt->bind_param('ss',$username,md5($password));
    
    $stmt->execute();
    $get_result =$stmt->get_result();
    
    $row_count= $get_result->num_rows;
    
    if ($row_count>0){
    
            session_start();
            $_SESSION['nID'] = true;
    
            header('Location: home.php');
             die();
    
        } else {
            echo"Login failed"; 
        }
    

    4th : Don't use Md5() for password. Try to use password_hash() and password_verify() Reference link

    while registration use password_hash() to hash the password and store it in database and while login use password_verify() to verify the password like this .Reference link

  5. Andy- Reply

    2019-11-16

    you need to add session_start(); in every page to get the session variables.

  6. Anthony- Reply

    2019-11-16

    You have to call session_start() function in the file where you are trying to use session variable.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>