http://www.perlmonks.org?node_id=751795

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

What's a good way to clean up the session files generated by CGI::Session? Some of these files are deleted when the users perform logout. If they don't, then these files just remain in the session folder and grow overtime.

Of course you want to make sure that only those that have expired are cleaned up. I'm thinking of using cron and reading the files' dates or something. But are there better solutions?

  • Comment on Suggestions on cleaning up session files

Replies are listed 'Best First'.
Re: Suggestions on cleaning up session files
by almut (Canon) on Mar 19, 2009 at 17:32 UTC
    I'm thinking of using cron and reading the files' dates

    That's exactly what I do. Works like a charm.

    Sample code:

    my $tmp_path = "/tmp/myapp"; my $max_age = 60*60*24; # e.g. one day my $t_keep = time() - $max_age; my @stale_sessfiles = grep { (stat $_)[9] < $t_keep } # files older than $t_keep glob "$tmp_path/cgisess_*"; # print STDERR "$_\n" for @stale_sessfiles; # debug unlink @stale_sessfiles;
      Thanks for your code :) You wrote "Sample code". Does it work as it? Do I have to make changes to it?

        Well, you might need to adjust $tmp_path and $max_age, and then configure things to have it run via cron.  You wouldn't risk much just giving it a try :) — there really isn't much to it, after all... And in case you're paranoid, you can always first comment out the unlink line, and uncomment the debug print to check what would be deleted...

Re: Suggestions on cleaning up session files
by sundialsvc4 (Abbot) on Mar 19, 2009 at 17:33 UTC

    That's the only way that I know to do it. However, it is partly for this reason that I use an SQL database to store session information. Not only is it tidier than "files," but it also gives you a very-direct way to store ancillary information such as expiry-dates.

    I do know that PHP's session-handler provides a way for you to set a random (small...) probability that session-file cleanup should be done automagically. At random intervals, someone somewhere gets stuck with the job. Personally, though, I think that a cron-based process is fairer and cleaner.

Re: Suggestions on cleaning up session files
by Bloodnok (Vicar) on Mar 19, 2009 at 17:34 UTC
    In both sh and perl scripts, for files that have the same expected longevity as the script itself, I tend to create temporary files with the creating PID in the filename and then remove these files at the end of the script - either via a trap command or an END block.

    A user level that continues to overstate my experience :-))
      Often in a CGI web application a user's session outlives several program invocations. It's important not to log a user out of a web application before the stated session time limit. Users are fickle beasts with a ravenous appetite for support techs. Please don't taunt them with easy access to the support department through a bug report.

      For temporary files that really don't outlive a single program, File::Temp can give you an open file handle for a file that will automatically get cleaned up without predictably placing the PID number in the file name. Temp file naming collisions are a security risk.

Re: Suggestions on cleaning up session files
by captsalty (Initiate) on Mar 19, 2009 at 21:30 UTC
    I do something like this in the code that creates a new session:
    if (int(rand 5) == 1) {
       $self->log->info('Purging old sessions from the DB');
    
       CGI::Session->find('driver:sybase', sub { }, {
          TableName => 'sessions',
          Handle => My::DB::Module::get_handle()
       });
    }
    
    Obviously tweak the number after rand to change the probability of running this code based on the popularity of your site. This keeps me from having to schedule yet another cron job to keep old sessions out of the DB.

    UPDATE: Just noticed you were referring to file-based sessions.. Haven't tried this approach there..

Re: Suggestions on cleaning up session files
by Utilitarian (Vicar) on Mar 23, 2009 at 13:31 UTC
    Another possibility is to use the find utility with cron.
    #! /bin/bash rm $(find /path/to/session-files/ -mtime 1)