PHP Session

Summary: in this tutorial, you will learn how to work with PHP sessions to preserve the state of the web application across pages during a session.

Introduction to PHP sessions

The HTTP protocol is stateless. For example, when you visit the product page product.php, the web server responds with the page:

Suppose, you click the add to cart button on the product.php page and navigate to the cart.php page, the web server won’t know that you have added the product to the cart.

To persist the information across the pages, the web server uses sessions. In this example, when you click the add to cart button, the web server will store the product on the server.

When you view the cart.php page, the web server gets the products from the session and displays them on the cart.php page:

How it works.

  • First, the web browser requests for the product.php page.
  • Second, the web server responds with the product.php page’s content.
  • Third, you click the Add To Cart button on the product.php page. The page will send an HTTP request (either POST or GET) to the web server. The web server validates the product and generates a session id. It also creates a new text file on the server to store the information related to the selected product.
  • Fourth, the web server responds to the web browser with the PHPSESSID cookie in the response header. If the web browser allows cookies, it will save the PHPSESSID cookie, which stores the session id passed by the web server.
  • Fifth, in the subsequent request, for example, when you view the cart.php page, the web browser passes the PHPSESSID back to the web server. When the web server sees the PHPSESSID cookie, it will resume the session with the session id stored in the cookie.
  • Finally, the web server returns the cart page with the products that you selected.

Sessions allow you to store data on the web server associated with a session id. Once you create a session, PHP sends a cookie that contains the session id to the web browser. In the subsequent requests, the web browser sends the session id cookie back to the web server so that PHP can retrieve the data based on the session id.

Creating a new session

To create a new session, you call the session_start() function:

<?php

session_start();Code language: HTML, XML (xml)

When the session_start() runs at the first time, PHP generates a unique session id and passes it to the web browser in the form of a cookie named PHPSESSID.

If a session already exists, PHP checks the PHPSESSID cookie sent by the browser, the session_start() function will resume the existing session instead of creating a new one.

Since PHP sends the PHPSESSID cookie in the header of the HTTP response, you need to call the session_start() function before any statement that outputs the content to the web browser.

Otherwise, you will get a warning message saying that the header cannot be modified because it is already sent. This is a well-know error message in PHP.

Where PHP stores session data

By default, PHP stores session data in temporary files on the web server. You can find the location of the temporary files using directive session.save_path in the PHP configuration file.

The ini_get() function returns the value of the session.save_path directive:

<?php

echo ini_get('session.save_path');Code language: HTML, XML (xml)

Or you can call the session_save_path() function:

<?php

echo session_save_path();Code language: HTML, XML (xml)

Typically, the session data is stored in the /tmp folder of the web server e.g, /xampp/tmp .

Accessing session data

Unlike cookies, you can store any data in the session. To store data in the session, you set the key and value in the $_SESSION superglobal array.

For example, in the index.php file, you store the user string and roles array in the session as follows:

<?php
	session_start();
	// store scalar value
	$_SESSION['user'] = 'admin';
	// store an array
	$_SESSION['roles'] = ['administrator', 'approver', 'editor'];
?>

<html>
<head>
    <title>PHP Session Demo</title>
</head>
<body>
    <a href="profile.php">Go to profile page</a>
</body>
</html>Code language: HTML, XML (xml)

How it works:

  • First, create a new session by calling the session_start() function.
  • Second, set the session data with the key user and roles to the ‘admin’ and the array ['administrator', 'approver', 'editor].

The index.php displays a link that navigates to the profile.php page. In the profile.php file, you can access session data as follows:

<?php session_start() ?>

<?php if (isset($_SESSION['user'])) : ?>
    <p>Welcome <?= $_SESSION['user'] ?></p>
<?php endif; ?>

<?php if (isset($_SESSION['roles'])) : ?>
    <p>Current roles:</p>
    <ul>
        <?php foreach ($_SESSION['roles'] as $role): ?>
            <li><?= $role ?></li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>Code language: HTML, XML (xml)

How it works.

  • First, resume an existing session created in the index.php file.
  • Second, accessing session data using the $_SESSION array.

Deleting the session data

Whenever you close the web browser, PHP automatically deletes the session. Sometimes, you want to explicitly delete a session, e.g., when you click the logout link. In this case, you can use the session_destroy() function:

<?php

session_destroy();Code language: HTML, XML (xml)

This  session_destroy() deletes all data associated with the current session. However, it does not unset data in the  $_SESSION array and cookie.

To completely destroy the session data, you need to unset the variable in  $_SESSION array and remove the PHPSESSID cookie like this:

<?php
session_start();

// remove cookie
if(isset($_COOKIE[session_name()])){
    setcookie(session_name(),'',time() - 3600, '/');
}

// unset data in $_SESSION
$_SESSION[] = array();

// destroy the session
session_destroy();Code language: HTML, XML (xml)

Notice that we used the session_name() function to get the cookie name instead of using the PHPSESSID. This is because PHP allows you to work with multiple sessions with different names on the same script.

Summary

  • Sessions allow you to persist data across pages in a web application.
  • Call the session_start() function before any statement that outputs to the web browser for creating a new session or resuming an existing session.
  • Use the $_SESSION superglobal array to access the session data.
  • Call the session_destroy() function to completely delete session data.
Did you find this tutorial useful?