PHP Sessions

· opensprocket's blog

Everything I wish I knew about PHP Sessions
#php

# Introduction

This blog post is a collection of things that I wish I had known before starting to use PHP Sessions with some practical examples. There are also some other PHP "nice to knows" sprinkled in which I found useful as PHP novice. By the end of this, I hope to convey the basics of using sessions in PHP.

# What is a Session?

A session is used to store information and activity for a website visitor. When you start a session, it allocates resources on the server to store the session and all of the associated data.

Each session is unique to that specific visitor and should be considered temporary. Sessions have a lifetime and once they expire or are terminated all data is discarded. Since every open session on the server consumes resources, It is considered best practice to to close or stop a session once it is no longer needed.

Examples of things that use sessions:

The default session timeout on an Apache PHP server is 1440 seconds or 24 minutes. Changing session timeout can negatively affect server availability and performance - ranging anywhere from degraded performance to crashing the server.

# Sessions vs Cookies

How are sessions and cookies different from each other? This table highlights some of the key differences between cookies and sessions:

Characteristic Cookies Sessions
Storage Location Stores information client side, considered "untrusted" Stores information server side, considered "trusted"
Storage Duration Long lasting, stays until expiration or user clears cookies Short lived, lasts until session times out or is terminated
How the data is accessed Data is sent back and forth with each HTTP/HTTPS request Data doesn't need to be sent back and forth with each HTTP/HTTPS request
Size Restrictions Limited to 4096 bytes No size limit
Data Persistance Data can persist across multiple visits Data persists across all pages while active

Note: Due to width constraints, you may need to scroll to see the other column.

As with anything involving architecture or design, there is no one right answer for which to use. Generally speaking, sessions are useful when trying do things which require high levels of security or need to interact with the same context across multiple windows or pages. Any time that you need something to last longer than the user is logged in and active on the site, cookies are a better choice. Taking the time to undertand the desired outcome or problem before coding will be time saved and frustration avoided later on.

# How to use Sessions

# Environment Setup

This tutorial assumes that you have a working PHP webserver. My development environment uses the following docker-compose.yml file on a Windows machine using WSL2 with Docker Desktop (Ubuntu 22.04.3 LTS) [1][2]:

1version: "3"
2services:
3    web:
4        image: php:apache
5        container_name: apache_php
6        ports:
7            - 4000:80
8        volumes:
9            - ./:/var/www/html

# Starting a Session

To start a PHP session, put start_session(); at the top of any PHP page that you want to use a session on like this:

1<?php
2// start/resume the session
3start_session();
4?>

start_session() is the function which starts and resumes sessions. This particular function has optional parameters that can be passed in, however calling it without parameters tells PHP to detect the session on its own.

It is important to put it before any other PHP code to ensure that the session is properly started/resumed. This prevents "footgun" errors[3] such as attempting to access session variables before initializing the session.

# Using a Session

When connected to a session you will have access to a special global array, $_SESSION. PHP arrays are associative, which means you can either use indexes (0, 1, 2, etc.) to access their contents or key-value pairs (e.g. $_SESSION["name"] = "John Doe";). Generally speaking, key-value pairs will be easier to use, since they allow for names that provide additional context.

To add something to the $_SESSION array, simply put $_SESSION followed by the key name in quotes (double and single quotes work) enclosed in [ and ]. Here's an example of what that could look like:

1<?php
2// start/resume the session
3session_start();
4
5// add values to the $_SESSON global array
6$_SESSION["key"] = "value";
7$_SESSION["iconic_song"] = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
8$_SESSION["music_genre"] = "Classic Rock";
9?>

# Accessing Session Data

To access data stored in the $_SESSION array, simply do the following:

1<?php
2// start/resume the session
3session_start();
4
5echo "My favorite music genre is " . $_SESSION["music_genre"] . ".";
6
7?>

PHP Tip: Concatenation in PHP is done using . between the things you want to merge together.

The above code prints out:

My favorite music genre is Classic Rock.

You can use $_SESSION variables anywhere you would be able to use a normal variable.

# Stopping a Session

To completely stop a session, three key things must be done according to the PHP manual [4][5]:

  1. Unset the session variables using session_unset()
  2. Destroy the session using session_destroy()
  3. Stop any pending writes to the session with session_write_close()

PHP Tip: You have to use start_session() before you can destroy your session - you won't be able to get to the session without it!

 1<?php
 2// start/resume the session
 3session_start();
 4
 5// removes all of the session variables
 6// does not remove from the users computer
 7session_unset();
 8
 9// removes all of the session data on the users computer
10session_destroy();
11
12// stop anything writing to the session
13session_write_close();
14?>

Using the above methods to close the sesion out will ensure that everything is removed and any of the state information cached on the client side. If you want to save anything from the session, that needs to be done before calling session_unset() and session_destroy().

# Closing Thoughts

These are the basics of session management I wish someone had shared with me when I started learning how to use PHP sessions. Learning best practices requires a willingness to research and learn what others are doing.

# Additional Resources

# Footnotes

# Additional Reading