How to use PHP Session to store data?

We’ve already learned what a session is, and now we’ll see how to use PHP to handle sessions.

How to handle sessions using PHP?

1. Start new or resume existing session

First, you have to call the PHP session_start() function to start a new or resume existing sessions.

<?php
session_start();

2. Create a new session (Store a new value)

A new session can be created with the help of the $_SESSION super-global variable. Let’s see how –

<?php
session_start();
// Syntax
$_SESSION['name'] = value;
nameWith the session name, you can access the session value.
valuevalue of the session. The value can be anything – number, string, boolean, array, etc.
<?php
session_start();
// Creating a new session
$_SESSION['email_id'] = '[email protected]';

3. Access the session value

The $_SESSION variable gives you an array that contains all the sessions, and with the help of the session name you can access a specific session value.

<?php
session_start();
// Creating new session
$_SESSION['email_id'] = '[email protected]';

// Accessing the session value
echo $_SESSION['email_id'];

You can access the session value from another script (page) also, like the following –

<?php
session_start();

// Accessing the session value from test.php
echo $_SESSION['email_id'];

4. Delete a PHP session

Delete a specific session – If you registered multiple sessions and want to delete a specific session, you can use the unset() function.

<?php
session_start();
// Creating new session
$_SESSION['email_id'] = '[email protected]';

// Deleting a session
unset($_SESSION['email_id']);

💡 Tip: You can delete a session from another script (page) also.


5. Destroys all the session data at once

The session_destroy() function is used to destroy all data registered to a session, but unset all of the session variables before calling this function.

<?php
session_start();
// Creating new session
$_SESSION['email_id'] = '[email protected]';

// Step 1: Unset all of the session variables.
$_SESSION = array();
// Step 2: Destroy the session.
session_destroy();