PHP Session Management

The Problem Of Persistance

We need a way to remember if a user is logged in through different points in time. Normally the web is a stateless environment, we can, however, use a PHP session to achieve this.

The Solution

Upon login, we are given a cookie session file that is also logged by the server. When we load a page content can be shown based on the access dictated in the session, or lack thereof. Sessions can be hijacked or spoofed using monitoring and cookie editors so care must be taken. Session data is often sent in the HTML header.


Scripts using sessions must start with:

ini_set("session.save_path", "/home/USERID/sessionData"); 

The path is for theory only, it is best to store in a folder with locked down permissions.

session_start(); creates a session with a sessionID and cookie, or resumes if a file exists in the path

if (isset($_SESSION['logged-in']) && $_SESSION['logged-in']) 
  // Do logged in action, e.g., display 
  // restricted content
  // Do not logged in action

We sometimes want to close the session manually. It is done by default when the browser is closed, usually. In the case we log out after a task or want to empty a shopping basket, for example, we need the following:

$_SESSION = array(); 

We can access and store data between pages using this concept, besides just login status. We can share variables and such which is incredibly useful. We write to the session array, which are then written as session variables to the session file that can then be accessed by other pages. We simply have to parse the info. If a session file is loaded, the session variables associated with the file are loaded into the $_SESSION array.

Writing To Session:

$_Session['username'] = 'John'; 

-> [file]sess_0u8t43h4uhthrcd3re94f9 -> username|s:4:"John";

Reading From Session:

if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    echo "<p>Username: $username</p>\n";

Security Tips:

  • Revalidate users before important tasks
  • Don't show truly sensitive data to those only validated by session ID
  • Don't allow session code in query strings Don't use session variables to store passwords and other sensitive data
  • Support logout and include session timeouts and regeneration.
  • Use SSL HTTPS to encrypt session ID communication
  • Put session files in a folder with restricted access and strong permissions
  • Ensure session generation is random, do not allow for nomenclature, that can be guessed for privilege escalation.