bash session killer

I ran into a problem with a site I’m building that will run on shared hosting. I wanted to use sessions in php but because of the hosting my sessions kept being unexpectedly ended. The solution was to define a new folder on the server for the sessions to be stored in. This was done with the php.ini configuration file.

However this lead to another problem – the session files just seemed to get left on the server. As I understand it this is because the garbage collection mechanism in php won’t work if you change the folder where session files are stored.

The solution was in a little bit of BASH scripting. Basically the script is run by the cron tab at a sensible interval. When it runs it checks the directory specified and deletes anything older than the number of mins specified.

1
2
#! /bin/bash
cd /path/to/folder/; find -cmin +60 | xargs rm

A word of warning, make sure you get the path right. First time round I didn’t and it deleted EVERYTHING it could on my server. I lost all development work and a live site. So back up and use with caution. Still at least it proved my backup strategy works ;-)

Don’t forget to make the .sh file executable (744) did it for me.


About this entry