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:



Table Of Contents