O'Reilly logo

Essential PHP Security by Chris Shiflett

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exposed Session Data

Even when you take care to protect your source code, your session data might be at risk. By default, PHP stores session data in /tmp. This is convenient for a number of reasons, one of which is the fact that /tmp is writable by all users, so Apache has permission to write session data there. While other users can't read these session files directly from the shell, they can write a simple script that can do the reading for them:

    <?php

    header('Content-Type: text/plain');
    session_start();

    $path = ini_get('session.save_path');
    $handle = dir($path);

    while ($filename = $handle->read())
    {
      if (substr($filename, 0, 5) == 'sess_')
      {
        $data = file_get_contents("$path/$filename");

        if (!empty($data))
        {
          session_decode($data);
          $session = $_SESSION;
          $_SESSION = array();
          echo "Session [" . substr($filename, 5) . "]\n";
          print_r($session);
          echo "\n--\n\n";
        }
      }
    }

    ?>

This script searches session.save_path for files that begin with sess_. When such a file is found, the contents are parsed and displayed with print_r(). This makes it easy for another developer to view the session data of your users.

The best solution to this particular problem is to store your session data in a database protected with a username and password. Because access to a database is controlled, this adds an extra layer of protection. By applying the technique discussed in the previous section, the database can be used as a safehaven for your sensitive data, although you should remain alert to the fact that the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required