Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/e0328bb04688cc39abb75f15b21c9b1d to your computer and use it in GitHub Desktop.
Save code-boxx/e0328bb04688cc39abb75f15b21c9b1d to your computer and use it in GitHub Desktop.
PHP Sessions Examples

PHP SESSIONS EXAMPLES

https://code-boxx.com/sessions-in-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) START SESSION
session_start();
// (B) SESSION VARIABLES
$_SESSION["hello"] = "world";
$hello = "world";
// (C) OUTPUT
print_r($_SESSION); // ["hello" => "world"]
echo $hello; // "world"
<?php
// (A) START/RESUME SESSION
session_start();
// (B) OUTPUT
print_r($_SESSION); // ["hello" => "world"]
echo $hello; // gone - undefined variable
<?php
// (A) START/RESUME SESSION
session_start();
// (B) APPEND TO SESSION
$_SESSION["name"] = "Jon Doe";
$_SESSION["colors"] = ["Red", "Green", "Blue"];
// (C) OUTPUT
print_r($_SESSION); // [hello, name, colors]
<?php
// (A) START/RESUME SESSION
session_start();
// (B) BAD WAYS TO ASSIGN SESSION VALUES
// $_SESSION = "hello";
// $_SESSION = 123;
// $_SESSION = ["hello", "world"];
<?php
// (A) START/RESUME SESSION
session_start();
// (B) SET SESSION VARIABLES
$_SESSION = [
"name" => "Jon",
"age" => 999,
"gender" => "Male"
];
print_r($_SESSION); // [name, age, gender]
// (C) UNSET
unset($_SESSION["age"]);
print_r($_SESSION); // [name, gender]
<?php
// (A) START/RESUME SESSION
session_start();
print_r($_SESSION);
// (B) END SESSION
session_destroy();
unset($_SESSION);
print_r($_SESSION); // cleared - undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment