简体   繁体   English

未定义的会话索引PHP

[英]Undefined Session Index PHP

I'm creating a login page. 我正在创建一个登录页面。 When I login the first time it redirects me to main.php. 当我第一次登录时,它会将我重定向到main.php。 When it does I get this from var_dump: string(7) "Francis" which is fine. 当它从var_dump中得到时:string(7)“ Francis”很好。 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']);). 但是,如果刷新main.php,则会收到此通知:未定义索引:path_to_file \\ main.php中第20行NULL的名字为(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 页面: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 页面: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 页面: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 页面: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. 刷新main.php时,会话消失。

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. 它与包含的“ validate_login.php”页面有关。 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();
 }
 ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM