HTTP is stateless, it can’t carry the values of variables of one page to other page and redirection with values is a basic requirement nowadays. For that we have many options if want to use values of one page across multiple pages.

One of the way is to use session. With session variable you can store information which can be used across multiple pages. Session temporary stores information and last up to user’s close the browser.

Sessions in PHP

PHP session start

Session Variable :

By default session do not start automatically. To work with a session, you need to explicitly start/stop or resume that session. To start a session, you have to write session_start() at the beginning of each code. After a session is started, you instantly have access to the user’s session ID via the session_id() function.

Example :

<?php
     session start();  // session started
     echo “Your session-id : ” . session_id();
?>

When you run this script first time, a session ID is generated and when the script is later reloaded or revisited, the same session ID is allocated to the user. Sessions remain current as long as the web browser is active.

Working with PHP Session Variables :

Once a session is started, you can store any number of variables in the $_SESSION superglobal and then access them on any session-enabled page.

Example :

<?php
   session_start();
   $_SESSION[‘product1’] = “HP Pen Drive”;
   $_SESSION[‘product2’] = “ScanDisk Pen Drive”;
?>

These values will not become apparent until the user moves to a new page. Lets create a separate PHP script that accesses the variables stored in the $_SESSION superglobal.

Example :

<?php
Session_start();
?>
<p>Your chosen products are:</p>
<ul>
<li><?php echo $_SESSION[‘product1’]; ?></li>
<li><?php echo $_SESSION[‘product2’]; ?></li>
</ul>

Destroying / unsetting Session Variables :

You can use session_destroy() to end a session, erasing all session variables. The session_destroy() function requires no arguments.
Example :

<?php
    session_start();
    $_SESSION[‘test’] = 5;
    session_destroy();
    unset($_SESSION[‘test’]);
    echo $_SESSION[‘test’]; // prints nothing
?>