What is a Session

PHP session is used to store and pass information from one page to another page temporarily.PHP session to you can create login and logout system, add to cart system etc.PHP session is store in server side.

Start a PHP Session

PHP session is easily started with the session_start() function.

$_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.

Set PHP Session Variable Values

Now, let's create a new page called demo1.php.

<?php
    // Starting session
    session_start();

    // Set session variables
    $_SESSION["name"] = "abc";
?>

Get PHP Session Variable Values

Now, let's create a new page called demo2.php.

<?php
    // Starting session
    session_start();

    // Get session variables
    echo $_SESSION["name"];
?>

Destroying a PHP Session

If you destroy a single session variable then you can use unset() function to destroy a session variable.

<?php
    // Starting session
    session_start();

    // Removing session data
    if(isset($_SESSION["name"])){
        unset($_SESSION["name"]);
    }
?>

PHP session can be destroyed by session_destroy() function. This function doesn't need any argument and a single call can destroy all the session variables.

<?php
    // Starting session
    session_start();

    // Destroying session
    session_destroy();
?>