A session is used to store information in variables. These php variables are used to store user information to be used across multiple pages. Unlike a cookie information is not stored in the user computer.PHP session is started by using session_start() function.

Now, let’s create a new page session.php
<?php                       

session_start(); // Start the session
$_SESSION["name"] = "Geeta"; // Set session variables
$_SESSION["age"] = "23";
echo "Session variables are set.";
?>
Output: 
Session variables are set.  
Get PHP session variable

We will create an another page (demo.php) from which we get the session variable from session.php

<?php

session_start();
?>
<?php
echo "My name is " . $_SESSION["name"] . ".<br>";// session variables that were set on previous page

echo "Age: " . $_SESSION["age"] . ".";
?>

  Output: 

My name is Geeta.

Age: 23.

Modify session Variable

To modify a session variable just overwrite.

<?php

session_start();
$_SESSION["name"] = "Ragini";// to modify a session variable
print_r($_SESSION);
?>

  Output: 

Array ( [name] => Ragini [age] => 23 )// Ragini will be overwritten

To destroy Session

To destroy session variable and session use session_unset() and session_destroy().

<?php

session_start();
session_unset();// remove all session variables
// destroy the session
session_destroy();
echo " Session variable are removed and session is destroyed "
?>

  Output: 

Session variable are removed and session is destroyed.


 

  Modified On Mar-15-2018 05:57:03 AM

Leave Comment