Skip to content

Instantly share code, notes, and snippets.

@carlosleonam
Last active July 30, 2021 18:00
Show Gist options
  • Save carlosleonam/5917b449c0ae6c493b81a44de3a4af7a to your computer and use it in GitHub Desktop.
Save carlosleonam/5917b449c0ae6c493b81a44de3a4af7a to your computer and use it in GitHub Desktop.
Force CLEAN session files in PHP server.

Force CLEAN session files in PHP server.

OPTION 1

Every 30 minutes, not on the hour

Grabs maxlifetime directly from `php -i`

doesn't care if /var/lib/php5 exists, errs go to /dev/null

09,39 * * * *   find /var/lib/php7.2/ -type f -cmin +$(echo "\`php -i|grep -i session.gc_maxlifetime|cut -d' ' -f3\` / 60" | bc) -exec rm -f {} \\; >/dev/null 2>&1

# The Breakdown: Only files: find /var/lib/php5/ -type f
# Older than minutes: -cmin
# Get php settings: $(echo "`php -i|grep -i session.gc_maxlifetime
# Do the math: |cut -d' ' -f3` / 60" | bc)
# RM matching files: -exec rm -f {} \;

OPTION 2

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment