php

Destroy PHP Session

When a user visits a website in the browser then the amount of time passed by that user on that website is called the session for that user. When a user closes the browser or logout from the site then the session expires. The session information can be stored by using a cookie on the client’s computer or by using the PHP script that is stored in the server. The information stored by the cookie can be hacked easily by unauthorized access. So, the way of storing session information using the cookie is unsecured. PHP has some built-in functions and session variables to keep and destroy the session information of the users. The way to unset session variable and destroy session of PHP has been shown in this tutorial.

Unset Session Variable

The particular session data can be removed by using the unset() function. The session_unset() function is used to erase all session-related data of a particular session. PHP uses $_SESSION associative array to keep the session data.

Syntax:

The syntax of the session_unset() function has given below.

It is used to unset the current session by erasing all session-related data from the $_SESSION array. It returns nothing.

Example-1: Unset session variable

Removing session by using the session_unset() function has shown in the following example. Create a PHP file with the following script create a session for the authenticated users and check a value of the $_SESSION array after destroying the session. A form is used in the script to take the username and password.

Next, these values will be compared with the specific values to check the authentication. A session will be created by using the session_start() function for the user if the username and password are correct. If the user will visit the web page then the session will be erased by using the session_unset() function to check the current session is destroyed or not.

<?php

//Check the form is submitted or not
if( isset($_POST['submit']))
{
    //Check the username and password fields are empty or not
    if( isset($_POST['un']) &&  isset($_POST['pw']) )
    {
        $username = $_POST['un'];
        $password = $_POST['pw'];

        //Check the authentication of the user
        if($username == 'admin' && $password == 'secret')
        {
       
            //Start session for the authenticated user
            session_start();
            echo "<center>";
            //Check the session variable
            if( isset($_SESSION['name']) )  
            {
                //Print welcome message
                echo 'Welcome back.<br>';
                //Unset the session for the user
                session_unset();  
                //Check the session variable after unset
                echo "The session value after unset : ".$_SESSION['name']."<br>";
            }
            else
            {
                //Set the session variable
                $_SESSION['name'] = 'Administrator';
                //Print the session variable
                echo "Session variable is set for ".$_SESSION['name']."<br>";
            }
            echo "</center>";
        }
        else
        {
            //Print error message for invalid user
            echo "<center>Username or password is not set</center><br/>";

        }
    }
}
else
{

?>

<html>
<body>
    <center><div>
        <h3>Unset session Example </h3>
        <form method="post" action="#">
            Username: <input type="text" name="un" />
            <br/><br/>
            Password: <input type="password" name="pw" />
            <br/><br/>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </div></center>
</body>
</html>

<?php
}
?>

Output:
The following output will appear after executing the above script. The user has to provide a valid username and password before submitting the form. According to the script, the valid username is ‘admin’ and the password is ‘secret’.

The following output will appear if the correct username and the password are submitted by the form and a new session will be generated for the user.

The following output will appear if the user re-visit the page again. If the session exists for the user then the user will get the message, ‘Welcome back’ and the session_unset() function will destroy the session for that user. The warning message will appear in the output because the session variable will be undefined after calling the session_unset() function. But this warning message can be omitted by using the error_reporting directive.

Destroy PHP session

The session_destroy() function is used to destroy all session variables of the visitors. It just destroys the session data but the PHP super-global variable, $_SESSION array contains the session data. The values of this array will be removed if the script is terminated or the user closes the session. The $_SESSION array can be created by initializing an empty array.

The PHPSESSID cookie may be kept in the user’s computer without any data after destroying the session if the browser cookie is enabled in the user’s computer. In this case, when the user will revisit the page again then a new session will be generated for the user even PHPSESSID cookie exists. The syntax of this function has shown below.

Syntax:

This function does not have any argument and it returns nothing.

Example-2: Destroying session using session_unset()

The way to destroy all types of session information using the session_unset() function has shown in the following example. Create a PHP file with the following script to create a default session for the general visitors, set session name and expiration date using setcookie() function, and print the session name after destroying the session using the session_unset() function.

<?php

//Start the session for the visitor
session_start();

//Set the Session Cookie for the visitor
if (session_id() != "" || isset($_COOKIE[session_name()]))    
    setcookie(session_name(), '', time() - 42000, '/');

//Print the default session name
echo "The default session name is ".session_name()."<br/>";
//Print the session expire date
echo "The session expire date is ".date('d-m-Y', time()+5000000)."<br/>";

//Destroy all session information
session_destroy();
if (session_id() == "")
    echo "Session has destroyed.";

?>

Output:

The following output will appear after executing the above script. Here, the session has been created with the expiration time and destroyed later by using the session_destroy() function.

Conclusion

Two ways to destroy PHP sessions have been explained in this tutorial with examples. The session_unset() and session_destroy() functions have been used in this tutorial to destroy any existing session. The PHP developer can use any of these functions to destroy sessions in PHP.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.