Looking for php Answers? Try Ask4KnowledgeBase
Looking for php Keywords? Try Ask4Keywords

PHP Manipulating session data


The $_SESSION variable is an array, and you can retrieve or manipulate it like a normal array.

// Starting the session

// 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";
// 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';

Also see Manipulating an Array for more reference how to work on an array.

Note that if you store an object in a session, it can be retrieved gracefully only if you have an class autoloader or you have loaded the class already. Otherwise, the object will come out as the type __PHP_Incomplete_Class, which may later lead to crashes. See Namespacing and Autoloading about autoloading.


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.