PHP Session

Session is a way to store information to be used across multiple pages. Session variables hold information and are available to all pages in one application.

Starting with PHP session

In order to create a session, you must first call the PHP session_start function and then store your values in the $_SESSION array variable.

session_start() - Start new or resume existing session.

bool session_start([array $options = []] )

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

$_SESSION - Session variables

An associative array containing session variables available to the current script.

Example: Store information in a Session variable

<?php 
   $_SESSION["user"] = "Vijay Singh";
?>

Example: Get information from Session variable

<?php 
   echo $_SESSION["user"];  // Vijay Singh
?>

file: session_file1.php

<?php 
   session_start();
?>
<html>
 <body>
 <?php 
   $_SESSION["user"] = "Vijay Singh";
 ?>
 <a href="session_file2.php">go to next page</a>
 <body>
 <html>

file: session_file2.php

<?php 
   session_start();
?>
<html>
 <body>
 <?php 
   echo "User: " .$_SESSION["user"];
 ?>
 <body>
 <html>

PHP Destroying Session

session_destroy() — Destroys all data registered to a session.

bool session_destroy (void)