News & UpdatesProgrammingWeb programming StoreMy Projects

PHP Tutorial – 16 – Sessions

A session provides a way to make variables accessible across multiple web pages. Unlike cookies, session data is stored on the server.

Starting a session

To begin a session the session_start function is used. This function must appear before any output is send to the web page.

<?php session_start(); ?>

The session_start function will set a cookie on the client’s computer containing an id used to associate the client with the session. If the client already has an ongoing session the function will resume that session instead of starting a new one.

Session array

With the session started the $_SESSION array can be used to store session data as well as retrieve it. As an example, the page view count can be stored with the code below. The first time the page is viewed the session element is initialized to zero.

  $_SESSION['views'] += 1;
  $_SESSION['views'] = 1;

This element can now be retrieved from any page on the domain as long as session_start is called on the top of that page.

echo 'Views: ' . $_SESSION['views'];

Deleting a session

A session is guaranteed to last until the user leaves the website. Then the garbage collector is free to delete that session. To manually remove a session variable the unset function can be used, and for removing all session variables there is the session_destroy function.

unset($_SESSION['views']); // destroy session variable
session_destroy();         // destroy session
Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours