
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/");
session_start();
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!