PHP clean-up of old sessions

Can someone explain the whole session clean up / max life of a session thing.

I have searched google/internet a lot - so please don’t just post a link to!!

I suppose I want to know how to control:
(1) when PHP automatically clears up individual set $_SESSION variables within a user’s logged in occasion (ie like unsetting one session)
(2) when PHP logs you out automatically for inactivity and clears the entire session (ie like session_destroy)

I think the php.ini settings that cover this are:

Is there a known problem for shared servers against dedicated - where you don’t have control on a shared of something? (I heard something about this)

How is the best way to set all this up so I can control the 2 things mentioned?

(I am sure in the past I have ignored this because it doesn’t work - but that could be the shared server problem)

When garbage cleanup runs, it clears sessions whose last-modified is expired (session.gc_maxlifetime).

(1): Are you talking about manually unsetting session vars? … unset($_SESSION[‘var’])
(2): Bump up session.gc_maxlifetime

Shared servers - know that simply by bumping up session.gc_maxlifetime does not guarantee your sessions will last that long. On many shared servers, sessions for every account are stored in the same directory (/tmp). Even though your account has a 2hr session.gc_maxlifetime, some of your sessions may be deleted after 15minutes because somebody else’s account has session.gc_maxlifetime set to 15min. Digg?

This is why if possible, its a good idea to ensure your sessions are stored in a non-web-accessible directory; but one where everybody else’s aren’t stored.
Me, each account on my server has its own tmp directory under their folder; For each account, I manually set the tmp directory through .htaccess. (Ex: /path/to/accountA/tmp/, /path/to/accountB/tmp)

How is the best way to set all this up so I can control the 2 things mentioned?
Custom php.ini, set it through .htaccess, or through PHP itself.

If you’re wondering how to do it through htaccess, well: (this may or may not work, depending on your server config)

php_value session.save_path "/var/www/vhosts/accountA/tmp"
php_value session.gc_maxlifetime "10800"

If you change the session.save_path to something other than the server’s default – does the standard garbage collection delete those when they expire? Or does garbage collection only delete expired sessions in the server default (e.g., /tmp)?

Yes the garbage collection will cleanup whatever you set the tmp directory to.
Otherwise I’d have thousands upon thousands of no-good-expired-wasting-space-on-my-server tmp files all over.

Bear in mind garbage collection is triggered with session_start() and it’s not guaranteed that it will actually be performed.


Garbage collection is IO heavy so you if you have 1000 pageloads a minute you probably want to set probability to about 0.1 percent or less.

Oh, good. That was exactly what I was concerned about.