Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cleanup php session files

Tags:

php

session

On my website I use PHP sessions. Session information is stored in files in my ./session path. After a few months I discovered that these session files are never deleted, by now there are 145.000 of them in this directory.

How should these be cleaned up? Do I have to do it programmatically, or is ther a setting I can use somewhere that would have this cleanup happen automatically?

EDIT forgot to mention: This site runs at a provider, so I don't have access to a command line. I do have ftp-access, but the session files belong to another user (the one the webserver proces runs I guess) From the first answers I got I think it's not just a setting on the server or PHP, so I guess I'll have to implement something for it in PHP, and call that periodically from a browser (maybe from a cron job running on my own machine at home)

like image 321
Jack Avatar asked Mar 17 '09 13:03

Jack


2 Answers

To handle session properly, take a look at http://php.net/manual/en/session.configuration.php.

There you'll find these variables:

  • session.gc_probability
  • session.gc_divisor
  • session.gc_maxlifetime

These control the garbage collector (GC) probability of running with each page request.

You could set those with ini_set() at the beginning of your script or .htaccess file so you get certainty to some extent they will get deleted sometime.

like image 71
Seb Avatar answered Oct 15 '22 07:10

Seb


Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5

# /etc/cron.d/php5: crontab fragment for php5 #  This purges session files older than X, where X is defined in seconds #  as the largest value of session.gc_maxlifetime from all your php.ini #  files, or 24 minutes if not defined.  See /usr/lib/php5/maxlifetime  # Look for and purge old sessions every 30 minutes 09,39 *     * * *     root   [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm 

The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this

#!/bin/sh -e  max=1440  for ini in /etc/php5/*/php.ini; do         cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/p' $ini 2>/dev/null || true);         [ -z "$cur" ] && cur=0         [ "$cur" -gt "$max" ] && max=$cur done  echo $(($max/60))  exit 0 
like image 25
Paul Dixon Avatar answered Oct 15 '22 06:10

Paul Dixon