0
votes

I have a login page where I've set a query to check if the login & password entered match the database. The user should only be able to see the homepage if they are logged in.

The PHP Login validation on the login page works fine (if user/pass does not exist, it shows the error message. If the combination is correct, it redirects to the homepage just as it should):

LOGIN PAGE

<?php

    define('DB_LOCATION', 'x');
    define('DB_USERNAME', 'x');
    define('DB_PASS', 'x');
    define('DB_NAME', 'x');

    $dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
        or die('Error connecting to database');

    $error_message= "";

    $user_name = $_POST['user'];
    $user_password= $_POST['pass'];

    if (isset($_POST['submit'])) {

        // ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
        if(!empty($user_name) && !empty($user_password)) {

        $query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";

        $result = mysqli_query($dbc, $query)
            or die ('Error querying username/password request');

            if(mysqli_num_rows($result) == 1) {

                session_start();

                $_SESSION['user'] = $row['user'];
                $_SESSION['pass']= $row['pass'];


                header("Location: http://test.ishabagha.com/LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");

            } // end if rows

            else {
                $error_message = "You were not able to log in";
            } // end else

        } // end query

    } // end isset

?>

My issue is that on the homepage, I want to make it so that if the username and password have not been set/accepted, it redirects back to the login page and the homepage is not viewable. This is what I put in the PHP header - even if I haven't previously logged in, it still shows the page instead of directing it back to the login page (where he header/location is specified) and does not keep the home page private.

HOMEPAGE

<?php

    define('DB_LOCATION', 'x');
    define('DB_USERNAME', 'x');
    define('DB_PASS', 'x');
    define('DB_NAME', 'x');

    $dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
        or die('Error connecting to database');

    session_start();

    $user_name = $_SESSION['user'];
    $user_password= $_SESSION['pass'];

    if(!isset($_SESSION['user']) && !isset($_SESSION['pass'])) {

        header("Location: /LESSON5/1%20-%20LOGIN.php");
     }


?> 

Please let me know what it is is that could be causing the second part of the code on the homepage from redirecting.

3
session_start(); should be top of your page - Saty
Put session_start() at top of page. - chandresh_cool
He has session_start in the rigt place - user557846
the problem is in your login page - $row does nothing, so your session arrays are never set. - Funk Forty Niner

3 Answers

2
votes

The problem is in your login page - $row does nothing, so your session arrays are never set.

You need to loop over $row

if(mysqli_num_rows($result) == 1) {

    while($row = mysqli_fetch_assoc($result)){
        $_SESSION['user'] = $row['user'];
        $_SESSION['pass']= $row['pass'];
    }
}
  • If mysqli_fetch_assoc fails, try mysqli_fetch_array().

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.


Footnotes:

  • You should NOT store passwords in sessions arrays.
  • Your session could be hijacked.

Read up on sessions hijacking:


Edit:

Place

$user_name = $_POST['user'];
$user_password= $_POST['pass'];

inside your conditional statement

if(!empty($user_name) && !empty($user_password)) {...}

yet, replacing that with

if(!empty($_POST['user']) && !empty($_POST['pass'])) {
    $user_name = $_POST['user'];
    $user_password= $_POST['pass'];

// rest of code you wish to execute

}

and also setting blank assignments first:

$error_message= "";

$user_name = "";
$user_password= "";

if (isset($_POST['submit'])) {

$user_name = $_POST['user'];
$user_password= $_POST['pass'];

that is why you are getting undefined index notices.

Also this

<form name =loginForm method="post" action="<?php echo $_SERVER[' PHP_SELF' ];?>">

remove name =loginForm - Forms do not have name attributes.

Important factor:

  • Change $_SERVER[' PHP_SELF' ] to $_SERVER['PHP_SELF'] that is a syntax error and your form will fail and redirect.
  • There should not be any spaces in there.

Edit #2: (rewrite)

Here is a rewrite:

<?php 

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

    session_start();

    define('DB_LOCATION', 'x');
    define('DB_USERNAME', 'x');
    define('DB_PASS', 'x');
    define('DB_NAME', 'x');

    $dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
        or die('Error connecting to database');

    $error_message= "";

    $user_name = "";
    $user_password= "";

    if (isset($_POST['submit'])) {

    $user_name = $_POST['user'];
    $user_password= $_POST['pass'];

        // ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
        if(!empty($user_name) && !empty($user_password)) {

        $query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";

        $result = mysqli_query($dbc, $query)
            or die ('Error querying username/password request');

            if(mysqli_num_rows($result) == 1) {

            while($row = mysqli_fetch_array($result)) {

                $_SESSION['user'] = $row['user'];
                $_SESSION['pass']= $row['pass'];

                }

                header("Location: /LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");
                exit;


        // echo "Welcome link here";


            } // end if rowns

            else {
                $error_message = "You were not able to log in";
            } // end else

        // Direct to other webpage

        } // end query



    } // end isset

?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Login</title>
  <link type="text/css" rel="stylesheet" href="/LESSON5/5_Signup_CSS.css">

</head>
<body>
<h1>Welcome to my website!</h1>
<h2>Please login below.</h2>
<h3>Don't have an account? <a href="/LESSON5/2%20-%20CREATE%20AN%20ACCOUNT.php">Create one here.</a></h3>

<div class="formFormat" >  
<div  id="table1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  <table id="cssTable">
    <tr>
        <td>Username:</td><td><input type="text" id="user" name="user" value="<?php echo $user_name; ?>" /></td>
    </tr>
    <tr>
        <td>Password:</td><td><input type="text" id="pass" name="pass" value="<?php echo $user_password; ?>"/></td>
    </tr>
      </table>

  </div>

  <div id="table2">

  <table> 
  <tr>
     <td><input type="submit" name="submit"/></td>
   </tr>
   <tr>
      <td id="createAccount"><a href="/LESSON5/2%20-%20CREATE%20AN%20ACCOUNT.php">Create an account</a></td>
   </tr>
   <tr>
    <td><?php echo $error_message ?></td>
   </tr>

  </table>
  </form>
  </div>
</div> 

<?php
//    mysqli_close($dbc);

if(isset($_SESSION['user']) && isset($_SESSION['pass'])) {

echo "Sessions are set";

}

else { 
  echo "Not set.";
}



?>

</body>
</html>

Passwords:

I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.

I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.

0
votes

For your home page:

  • If your session does not contain user and password, two assignment statements may print out some errors.
  • You need an exit right after the redirect header to make sure that script will not print out any more output.

Consider this code:

<?php

    define('DB_LOCATION', 'x');
    define('DB_USERNAME', 'x');
    define('DB_PASS', 'x');
    define('DB_NAME', 'x');

    $dbc = mysqli_connect(DB_LOCATION, DB_USERNAME, DB_PASS, DB_NAME)
        or die('Error connecting to database');

    if(session_id() == '') {
        session_start();
    }

    if(!isset($_SESSION['user']) || !isset($_SESSION['pass'])) {
        header("Location: /LESSON5/1%20-%20LOGIN.php");
        exit(); // make sure that there is nothing printed after location header
    }

    $user_name = $_SESSION['user'];
    $user_password= $_SESSION['pass'];


?> 
-2
votes

Place session_start() at the top of both pages. By the way - no need to store password in the session,only user name and/or id.

Another problem, is that your code is vulnerable to sql injection. Use prepared statement to prevent this.