-4

I come from a classic ASP programming background and boy PHP is really frustrating. What's the deal with PHP Sessions? In Classic ASP you Simply put:

<% Session("Name") = "XYZ" %>

And that Session is always available unless you kill it or it times out. With PHP I get a Session to work from one page to another but when I refresh the page I lose my session. Here is the code I have:

Page: modules.php

// Start the session
session_start();

Page: index.php

include 'modules/modules.php';

$_SESSION['username'] = "MyName";

if (isset($_SESSION['username']) && !empty($_SESSION['username']) {
    header('Location: main.php');
}

Page: main.php

include 'modules/modules.php';

echo "My username: ".$_SESSION['username'];
exit();

Now because I gave Session Username a default value it will redirect to main.php and it shows the username fine. But if I refresh the page it disappears. I ran this to see if there was any errors in the modules.php page right below the start session:

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

None were returned. But I can't figure out why my PHP Sessions just disappear. I am trying to create a login page where the user will login and his/hers info will be carried along each page so I can have there ID info and to make sure they are logged in. So could someone please tell me what I am doing wrong?

My Modules Page:

 // Start the session
 session_start();

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

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

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


 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)) {

     $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*/
}

}

Frank G.
  • 1,519
  • 7
  • 25
  • 43
  • 3
    `$_SESSION` is not a function, it's an associative array. Use `[` and `]` instead of `(` and `)`. – Alexander O'Mara Nov 13 '15 at 07:22
  • Okay so what am I doing wrong then? I corrected the code for ['username']. – Frank G. Nov 13 '15 at 07:24
  • `$_SESSION('username')` -> `$_SESSION['username']` – Alexander O'Mara Nov 13 '15 at 07:25
  • @AlexanderO'Mara I corrected the code above. But what would cause my session to disappear if I refresh the page? – Frank G. Nov 13 '15 at 07:27
  • What else does the modules.php file contain? – Repox Nov 13 '15 at 07:28
  • @Repox it contains functions for logging in, the database connection function and create an account function. – Frank G. Nov 13 '15 at 07:29
  • I'm looking for anything that might reveal that you have some output before `session_start()` - if we don't have the real code you're experiencing trouble with, people are just guessing. – Repox Nov 13 '15 at 07:30
  • @Repox I don't I load the module.php at the top of the index and main page. In the module page the session start is the very first thing to be ran. – Frank G. Nov 13 '15 at 07:40
  • @Repox I posted my module above. As for index and main that is the code. I am learning php as I said I come from an Classic ASP background and need to start learning php. So I am creating a basic test login. – Frank G. Nov 13 '15 at 07:43

1 Answers1

0

You're calling $_SESSION as if it were a function - $_SESSION("username") - while it's actually an array.

You should use $_SESSION["username"] to get the variable value.

You should be getting a Fatal error: Can't use function return value in write context ... but you probably did something wrong with turning on error reporting and you're not getting any errors.

The correct working code would look like this:

<?php
session_start();

if (isset($_SESSION["username"]) && !empty($_SESSION["username"])) {
    echo "My username: ".$_SESSION["username"];
} else {
    echo "Not set";
    $_SESSION["username"] = "MyName";
}
Andrius
  • 5,934
  • 20
  • 28
  • Sorry I corrected the code. I couldn't copy mine because I have sensitive info so I created an example here. And messed up the ['username']. I corrected it above. But why would my session disappear if I refresh the page? – Frank G. Nov 13 '15 at 07:27
  • Is your session even being saved? http://stackoverflow.com/questions/19692157/session-variables-not-working-php – Hanky Panky Nov 13 '15 at 07:29
  • @FrankG You can't expect anyone to have a solution for you if you're modifying the code for presentational use; share the code that you're having issues with - the sessions are probably fine, it's the surrounding code that doesn't work. – Repox Nov 13 '15 at 07:29
  • @Repox yes I understand but I have sensitive info in my modules.php file that I can't post and if I did I would have to modify it anyways. The example I show is pretty much the way it is working. I will post my modules above now so u can see my modules page. – Frank G. Nov 13 '15 at 07:31
  • @Andrius the session works but when I get to main.php the first time it shows the value. If I refresh the page the session disappears. I'm trying to figure out why it is disappearing on me. It shouldn't because its a Session. – Frank G. Nov 13 '15 at 07:41
  • @Andrius yes again the session works fine from index.php to main.php. But once I'm on main.php and refresh the page my session disappears. The code you have above will work 100% but that's not my problem!! – Frank G. Nov 13 '15 at 07:45
  • So, what you're saying is is you set the session in X.php, then you open Y.php with the same exact code that I have provided, and you do not have the session variable set there anymore? – Andrius Nov 13 '15 at 07:47