Home > Back-end >  $_SESSION variable not setting value
$_SESSION variable not setting value

Time:10-10

[RESOLVED]
In my login.php, several $_SESSION variables are set.
I've recently added in another = $_SESSION['darkM'] = false;.
Doing a var_dump($_SESSION); (Results below), my other variable's values are set perfectly but this one just will not!

I've tried setting it to a string instead ('test') but still returns empty in the var_dump. It is only this variable that will not set.
I've checked my error_log and there is nothing! Just to clear up, session_start(); is already set just above where I declare my variables. Any idea why this could be happening?


----- EDIT -----

Login.php:

<?php
session_start();

   // Store data in session variables
   $_SESSION["loggedin"] = true; // No error
   $_SESSION["tenant"] = $tenant; // No error
   $_SESSION['darkM'] = false; // Also tried setting to 'test'

VAR_DUMP($_SESSION) :

Array ( [loggedin] => 1 [tenant] => Coledon  [darkM] => )

RESOLVED

I have no idea why this made any difference, but I changed the variable from $_SESSION['darkM'] to $_SESSION['dark_mode']. Doing another var_dump the new result is: array(1) { ['dark_mode']=> bool(false) }

So I no longer have an issue, but still have no idea why this happened? There was no typing issues/hidden characters.
Also if anyone has this same problem please see navnath's & Reflective's answers - important to remember!

CodePudding user response:

No problem at all, just print_r treats false differently than you may expect. Use var_dump as it shows the value and type of the variables instead of converting them to string which print_r does.

<?php
    session_start();
    $_SESSION['darkMode'] = false;
    print_r($_SESSION);
    var_dump($_SESSION);
?>

Output

Array
(
    [darkMode] => 
)

array(1) {
  ["darkMode"]=>
  bool(false)
}

CodePudding user response:

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

Doc

  • Related