0

PHP session array created from database and want to print to screen only one variable. I'm using this guide.

The array is created by :

$user = $libUsr->check($_POST['email'], $_POST['password']);
if ($user===false) { echo "ERR"; }
else {
$_SESSION['user'] = [
"name" => $user['user_name'],
"email" => $user['user_email'],
"status" => $user['user_status'],
"data" => $user['user_data']
];
echo "OK";
}
break;

The header of the signedin page after login is below, with start_session() called in 2a-config.php

require __DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "2a- 
config.php";
if (!is_array($_SESSION['user'])) {
header("Location: index.php");
die();
}

I've tried all combinations such as these (with the php tags of course):

echo $user["name"];
echo $user[1]["name"];
print_r(array_column($user, ‘name’));

Was even getting desperate as I've spent a lot of time on this and no other answers I found was working so was even trying

echo $_SESSION["name"];
echo $_SESSION[1]["name"];

As well as these previously asked questions but still can't get it to work and no errors are coming up in my error log.

This is the array when I var dump.

ARRAY(1) { ["USER"]=> ARRAY(4) { ["NAME"]=> STRING(4) "TEST" ["EMAIL"]=> 
STRING(13) "TEST@TEST.COM" ["STATUS"]=> STRING(1) "A" ["DATA"]=> 
STRING(32) "9529C449206201FDBCE28CFA42FD48C8" } }

All I want is to just print the array variable "NAME" which is TEST to the screen. I'm hoping then I can workout how to pull out the user email in order to update my database. As you can see I'm a first time poster on Stack Overflow so apologies if my question is lacking. Thank you.

dc14
  • 3
  • 2
  • Whats `print_r($_SESSION)` show? – Lawrence Cherone May 02 '19 at 21:02
  • 1
    The key of your array is `user` so you can get your data with `$_SESSION['user']['name']` – fdehanne May 02 '19 at 21:05
  • Possible duplicate of [How to get single value from PHP array](https://stackoverflow.com/questions/4383914/how-to-get-single-value-from-php-array) – miken32 May 02 '19 at 21:21
  • Yes @fdehanne, that is it. Thanks very much! The other question I was looking at had that but I'm so new to php I couldn't assign it to my own. Really appreciate it, thanks – dc14 May 02 '19 at 21:21

1 Answers1

0

How about:

echo $_SESSION["user"]["name"];
tadman
  • 208,517
  • 23
  • 234
  • 262
andrunix
  • 1,704
  • 1
  • 14
  • 23
  • yes that's it, thanks very much - I see now the same logic is on the others but I'm a rookie so couldn't apply it to my own. I'll remove this as it's a duplicate. Thank you for the answer though! – dc14 May 02 '19 at 21:23