PHP sessions on shared hosting – Hack It! #3


If you use sessions with PHP on shared hosting, there are a couple of potential issues:

  • You might be vulnerable to session hijacking. PHP stores sessions as files. Where are they being stored? If they are stored in a publicly readable directory such as /tmp (the default), then other users of your shared host can hijack any session from your website. The session ID is part of the filename, so an attacker can build his own cookie that will be authenticated by your website.
  • You don’t have control over session timeouts. The default session timeout is 24 minutes. From the php manual: “If different scripts … share the same place for storing the session data then the script with the minimum value will [determine the session timeout]“.

So… by default, sessions timeout after 24 minutes, which I think many users would find pretty irritating, and you are vulnerable to session hijacking from anyone having access to your shared server.

Not good!

The solution. Here is one way to solve both of these potential issues. Whenever your code starts handling a session, include the following PHP:

ini_set("session.gc_maxlifetime","21600"); // 6 hours
ini_set("session.save_path", "/your_home/your_sessions/");

The first setting is the timeout in seconds, so for each hour of session survival, add 3600.

The second setting is the path to save session files to. Change this to a real directory in your home directory. Note that the first setting will not work unless you set this. Also note that the process running PHP needs to be able to write to this directory.

With this hack you can increase the security of your PHP sessions, and have them timeout over a period appropriate to your website. Hurrah!

3 Responses to “PHP sessions on shared hosting – Hack It! #3”

  1. harry says:

    sweet, after reading for hours, this helps clear up a lot.

    my only question, with this hack, i am now moving my session files to a www/ folder. i can password protect it i guess, but it is now open to public hacking.

    do you know what safeguards i can use in this case?

  2. peter says:

    Hey Harry,

    If at all possible, don’t put your sessions under your www directory – as you said, this exposes them to the outside world. Not good!

    If you must put your session directory under www, definitely password protect it with htaccess. There’s probably even a “no access” directive you can put in your .htaccess file.

  3. Brian says:

    Excellent tip. Just used it on a mini project I’m working on. :)

Leave a Reply