Manipulating session data
suggest changeThe $_SESSION variable is an array, and you can retrieve or manipulate it like a normal array.
<?php
// Starting the session
session_start();
// Storing the value in session
$_SESSION['id'] = 342;
// conditional usage of session values that may have been set in a previous session
if(!isset($_SESSION["login"])) {
echo "Please login first";
exit;
}
// now you can use the login safely
$user = $_SESSION["login"];
// Getting a value from the session data, or with default value,
// using the Null Coalescing operator in PHP 7
$name = $_SESSION['name'] ?? 'Anonymous';
See the array manipulation notes for more ways to work with an array.
An object stored in the session unserializes only if its class is already loaded or an autoloader can load it. Otherwise it comes back as __PHP_Incomplete_Class, which can later crash. See namespacing and autoloading.
Warning:
Session data can be hijacked. This is outlined in: Pro PHP Security: From Application Security Principles to the Implementation of XSS Defense - Chapter 7: Preventing Session Hijacking So it can be strongly recommended to never store any personal information in $_SESSION. This would most critically include credit card numbers, government issued ids, and passwords; but would also extend into less assuming data like names, emails, phone numbers, etc which would allow a hacker to impersonate/compromise a legitimate user. As a general rule, use worthless/non-personal values, such as numerical identifiers, in session data.