Manipulating session data

suggest change

The $_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';

Also see http://stackoverflow.com/documentation/php/6825/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 http://stackoverflow.com/documentation/php/504/classes-and-objects/6315/namespacing-and-autoloading#t=201611011543500298544 about 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Sessions:
* Manipulating session data

Table Of Contents
2 Arrays
4 Types
9 Sessions
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR