0

I'm creating a login page. When I login the first time it redirects me to main.php. When it does I get this from var_dump: string(7) "Francis" which is fine. But if I refresh main.php I get this Notice: Undefined index: firstname in path_to_file\main.php on line 20 NULL which is (var_dump($_SESSION['firstname']);). Why is a Session working the first time then failing/disappearing on refresh?

Here is the code:

Page: finishline_module.php

  <?php
  /*****************************************************/
  /* This module was created on 10/20/2015 at 1:40AM.  */
  /*****************************************************/

  // Start the session
  session_start();

  /**************************/
  /* Create System Settings */
  /**************************/

  /* Database Connection Settings */
  $_SESSION['servername']     = "localhost";
  $_SESSION['mysql_username'] = "xxxxxxxxxxxxx";
  $_SESSION['mysql_password'] = "xxxxxxxxxxxxx";
  $_SESSION['dbname']         = "xxxxxxxxxxxxx";

  //Turn on Error Report. True = On / False = Off
  ErrorReporting(true);

  //Display PHP Errors.
  function ErrorReporting($ErrOn){
      if ($ErrOn == true) {
          //Show Error
          ini_set('display_errors',1);
          ini_set('display_startup_errors',1);
          error_reporting(-1);
      }
  }

  /**************************************
  Open Database Connection Function.
  ***************************************/
  function db_conn($servername, $mysql_username, $mysql_password, $dbname) {
      $conn = mysqli_connect($servername, $username, $password, $dbname);

      // Check connection
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);

      // Test if connection succeeded
      if(mysqli_connect_errno()) {
          die("Database connection failed: " . 
               mysqli_connect_error() . 
               " (" . mysqli_connect_errno() . ")"
          );
      }
  }

  /**************************************
  Close Database Connection Function.
  ***************************************/
  function db_disconn() {
    $conn = null;
  }

  /***************************************
  Employee Login Check:
  ****************************************/
  function CheckLogin($strUserName, $strPassword) {

  if (isset($strUserName) && !empty($strUserName) && isset($strPassword) && !empty($strPassword)) {

        /*db_conn("localhost", "FinishLine2015!$", "Knuckle$20025272",       "nj_finishline2015"); Open db*/
          $conn = new mysqli($_SESSION['servername'],       $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);
      // Check connection
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      } 

              $sql = "SELECT id, firstname, lastname, user_name, password FROM tbl_employees WHERE user_name='$strUserName' AND password='$strPassword' AND account_disabled='';";
              $result = $conn->query($sql);

          //Check and see if there are records avaiable.
          if ($result->num_rows > 0) {
              // output data of each row with a loop.
              while($row = $result->fetch_assoc()) {

                  //Store the info into a session variable.
                  $_SESSION['eid']      = $row["id"];
                  $_SESSION['firstname']    = $row["firstname"];
                  $_SESSION['lastname'] = $row["lastname"];

                  return $_SESSION["eid"];
                  //break; //Stop the loop process.
              }
          } else {
                //No records found prompt the user.
                  return "User name or Password was Incorrect! Please try again!";
          }
          db_disconn(); /*Close db*/
      }
  }
  ?>

Page: index.php

<?php
//Included file.
include 'modules/finishline_module.php';
include 'modules/validate_login.php';

//Turn on Error Report. True = On / False = Off
ErrorReporting(true);

//Grab Login Info and store into a variable.
if (isset($_POST["username"]) && !empty($_POST["username"]) &&     isset($_POST["password"]) && !empty($_POST["password"])) {
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
}

//Use to test username and password output.
    //if (isset($_POST["username"]) && !empty($_POST["username"]) &&     isset($_POST["password"]) && !empty($_POST["password"])) {
    //  echo $username." ".$password;
    //  exit();
    //}

//Check if a value was entered for username and password.
if (isset($username) && !empty($username) && isset($password) &&         !empty($password)) {
    //Call function to log user in.
    $strLogin = CheckLogin($username, $password);

    if ($strLogin != ""){
        header('Location: main.php');
    }
}
?>

<html>
<head>
<title>XXXXX Online</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script Language="JavaScript">

var popup="This Site Copyright © protected 2015 XXXXXX all rights reserved."; function noway(go) 
{ if 
(document.all) { if (event.button == 2) { alert(popup); return false; } } if         (document.layers) 
{ if (go.which == 3) { alert(popup); return false; } } } if     (document.layers) 
{ document.captureEvents(Event.MOUSEDOWN); } document.onmousedown=noway; 

function validRequired(formField,fieldLabel)
{
  var result = true;

  if (formField.value == "")
  {
    alert('Please enter a value for the "' + fieldLabel +'" field.');

    formField.focus();

    result = false;
  }  
  return result;
}


function validateForm(theForm)
{

  if (!validRequired(theForm.username,"User name"))
   return false;

  if (!validRequired(theForm.password,"Password"))
    return false;

  return true;
}
</script>
        <link href="css/xxxxx.css" rel='stylesheet' type='text/css' />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script type="application/x-javascript"> addEventListener("load",     function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){     window.scrollTo(0,1); } </script>
        <!--webfonts-->
        <link href='http://fonts.googleapis.com/css?    family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
        <!--//webfonts-->
</head>
<body>

<!-----start-main---->
     <div class="main">
        <div class="login-form">
            <h1>Finish Line Member Login</h1>
                    <div class="head">
                        <img src="menubar/finish_line_logo_trans.gif" alt=""/>
                    </div>
                <form name="formlgin" method="post" action="index.php" onSubmit="return validateForm(this)" id="formlgin">

                        <input type="text" value="Knuckles02" name="username" class="text" placeholder="Username" onFocus="this.value = '';">
                        <input type="password" value="12345" name="password" placeholder="Password" onFocus="this.value = '';">
                        <div class="submit">
                            <input type="submit" onClick="myFunction()" value="LOGIN" >
                    </div>  
                </form>
            </div>
            <!--//End-login-form-->

        </div>
             <!-----//end-main---->
</body>
</html>

Page: main.php

<?php
//Included file.
include 'modules/finishline_module.php';
include 'modules/validate_login.php';

//Turn on Error Report. True = On / False = Off
ErrorReporting(true);
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Finish Line CMS</title>
</head>

<body>

<?php
var_dump($_SESSION['firstname']);

if (isset($_SESSION['firstname']) && !empty($_SESSION['firstname']) &&     isset($_SESSION['lastname']) && !empty($_SESSION['lastname'])) {
    echo "Welcome Back: ".$_SESSION['firstname']." ".$_SESSION['lastname'];
}
?>

</body>
</html>

Page: validate_login.php

<?php
if (isset($_SESSION['eid']) && !empty($_SESSION['eid'])) {
    // Finally, destroy the session.
    session_destroy();
}
?>

The Problem:

Session disappears when refreshing main.php.

1 Answer 1

1

Okay I figured out what is happen and why I am losing my sessions after it just worked the first time then would toss and error when refreshing the page. It has to do with the included "validate_login.php" page. It was destroying the sessions when I refreshed causing the error Undefined Index. Here is the code causing the problem:

 <?php
 if (isset($_SESSION['eid']) && !empty($_SESSION['eid'])) {
      // Finally, destroy the session.
      session_destroy();
 }
 ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.