Last updated on January 17th, 2023 at 02:37 pm

A PHP session can be used to store information or change settings for a user. Usually a session variables hold data about one single user, and are available to all pages in one application. Below script will help you understand on how to store, retrieve and delete session value in php.

Table of Contents

Create Session

Here we are going to create a session for Car type “Infinity” with available colors in an array.

Let us call the file set_session.php, once you add the below script to this file. Load the page in browser

Note that session_start() should be added first at the top of the page even before any HTML gets loaded. This has to be followed when you create, retrieve or delete sessions.

// start new session
// add session variables
$_SESSION['type'] = "Infinity";
$_SESSION['colors'] = array("green", "white", "blue", "yellow");
echo "Session type and colors are set";
echo "<br>Now go to this link <a href='get_session.php'>Get The Session</a>";

You should see a similar page like the one below

Get Session

Now that we have the session saved by loading the page above, we are going to retrieve those session variables using the below code, name it get_session.php

if (isset($_SESSION['type']) && isset($_SESSION['colors'])) {
// do something with them
echo "You would like a " , $_SESSION['type'] , " Car in " ,
implode(" or ", $_SESSION['colors']);
echo "<p><font color='red'>Delete Session <a href='destroy_session.php'>Click Here</a>";
	echo "Going Back To <b>set_session.php</b> page in 2 seconds since the session is not set";

In this code we are checking whether the sessions are set using isset($_SESSION[‘type’]) && isset($_SESSION[‘colors’]). As you can see we are also using implode() to print the values inside the array.

Delete Session

Now that we have created and retrieved session data the next step is the delete the session with the file named destroy_session.php. This destroys all data associated with current session. 



Leave a Reply

Your email address will not be published. Required fields are marked *