How to Unset Session Variable in PHP?

How to Unset Session Variable in PHP?

How to Unset Session Variable in PHP?

Cookies are the best way to store data and personalize the content for the end user. But there’s a possibility that a hacker may insert some malicious codes into the code for their own benefit. So is there a safer approach? Yes, and it is the PHP session stored on the server. And the best part is you can use this session for website-wide purposes. In this article, we’ll explore more about PHP Unset session variable and how you can use it for your own website.

How sessions works in PHP?

Before working with Unset session variable, let’s first work with how sessions work in PHP in the first place. By definition, sessions store information temporarily either on the server or computer. These temporary data are stored in a folder. The location is set by the php.ini file which has a setting called sessions,save_path. It’s required that you set a path before working with sessions.

When a user logs out of the browser or closes it, the session is terminated. Every different user is assigned a unique sessions ID to better identify the user. These are then linked with their posts and emails.

The sessions ID are automatically generated by the PHP engine.

Here’s what a session code will look like in PHP:

Code:
<?php
// start a new session
session_start();
// Check if the session name exists
if( isset($_SESSION['name']) ) {
echo 'Session name is set.'.'<br>';
}
else {
echo 'Session name not set!'.'<br>';
}
echo'<br>';
$_SESSION['name'] = 'Haley';
//unset($_SESSION['name']);
echo "Session Name : ".$_SESSION['name'].'<br>';
?>
Output:
Session name is set
Session name: Haley

In the above code, a new session starts with the session_start() function that invokes it. This is always written at the forefront of every code. The function has a sessions ID which you can access using the echo session_id() code.

The $_SESSION is used to clear the session variable when the user is done with what he is up to and closes the session.

If you uncomment the last line of the code like this:

Code:
unset($_SESSION[‘name’]);
echo “Session Name : ” .$_SESSION[‘name’];
Then the output will be:

Code:
Session name is not set!
For destroying the session variable created above, you need to use the following code:

Code:
session_destroy();
But for clearing or freeing up space that’s being consumed by the session variable, you should be using:

Code:
session_unset();
Therefore the PHP Unset session variable is use to clear the session that was created by the PHP engine.
Author
bhawanisingh
Views
11,770
First release
Last update
Rating
0.00 star(s) 0 ratings
Top